mongoose only saving _id and __v

900 views Asked by At

I am making an API using nestjs and mongoose. However, I am stuck on a bug. I have asked other people for help, and have tried googe with no luck. In short, my issue is that when making a POST request to the API endpoint, it only saves teh _id and __v in mongoose. Additionally, it only does this on this specific endpoint.

Here is relevant code:

application.schema.ts

import { Prop, SchemaFactory } from "@nestjs/mongoose";
import mongoose, { Document } from 'mongoose';

export type ApplicationDocument = Application & Document

export class Application {

    @Prop({ required: true, unique: true, type: mongoose.Schema.Types.ObjectId })
    id: string;

    @Prop({ required: true })
    event: string;

    @Prop({ required: true })
    user: string;

    @Prop({ required: true})
    start: string;

    @Prop({ required: true})
    end: string;

    @Prop({ required: true})
    positionsRequested: string[];

    @Prop({ required: true})
    facilitiesRequested: string[];

    @Prop({ required: true})
    notes: string;
}

export const ApplicationSchema = SchemaFactory.createForClass(Application);

createApplication.dto.ts

import { ArrayNotEmpty, IsArray, IsNotEmpty, IsString } from "class-validator";

export class CreateApplicationDto {

    @IsString()
    @IsNotEmpty()
    event: string;

    @IsString()
    @IsNotEmpty()
    user: string;

    @IsString()
    @IsNotEmpty()
    start: string;

    @IsString()
    @IsNotEmpty()
    end: string;

    @IsString({ each: true })
    @IsArray()
    @ArrayNotEmpty()
    positionsRequested: string[];

    @IsString({ each: true })
    @IsArray()
    @ArrayNotEmpty()
    facilitiesRequested: string[];

    @IsString()
    @IsNotEmpty()
    notes: string;
}

events.controller.ts

@Post('applications')
    postApplications(@Body() dto: CreateApplicationDto) {
        return this.eventService.postApplications(dto)
    }

events.module.ts

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { EventsController } from './events.controller';
import { EventsService } from './events.service';
import { ApplicationSchema } from './schemas/application.schema';
import { EventsSchema } from './schemas/event.schema';
import { AllocationSchema } from './schemas/allocation.schema';

@Module({
    imports: [
        MongooseModule.forFeature([
            { name: 'events', schema: EventsSchema },
            { name: 'applications', schema: ApplicationSchema },
            { name: 'allocations', schema: AllocationSchema }
        ])
    ],
    controllers: [
        EventsController
    ],
    providers: [
        EventsService
    ],
    exports: [
        EventsService
    ]
})
export class EventsModule {}

events.service.ts

constructor(
        @InjectModel('events')
        private eventsModel: Model<EventDocument>,
        @InjectModel('applications')
        private applicationsModel: Model<ApplicationDocument>,
        @InjectModel('allocations')
        private allocationsModel: Model<AllocationDocument>
        ) {}

// ... irrelevant code ...

async postApplications(dto: CreateApplicationDto): Promise<Application> {
        try {
            // Check for duplicate
            let dup: Array<object> = await this.applicationsModel.find({
                dto
            })
            // If duplicate found, not allowed
            if (dup.length > 0) throw new ForbiddenException("Application Already Submitted")

            // Get event
            let event = await this.eventsModel.findOne({ sku: dto.event })

            // If no event, return 404
            if (!event) throw new NotFoundException()

            let eventStart = event.start
            let eventEnd = event.end 


            if (
                // Start before end
                !(new Date(dto.start).getTime() < new Date(dto.end).getTime()) ||
                // Start and end during event
                !(new Date(dto.start).getTime() >= new Date(eventStart).getTime() && 
                  new Date(dto.end).getTime() <= new Date(eventEnd).getTime())
            ) throw new ForbiddenException("Incorrect start or end")

            const app = new this.applicationsModel(dto);
            return app.save()
        } catch (err) {
            throw err
        }
    }

whats being saved in mongo whats being saved in mongo

Thanks for any help!

2

There are 2 answers

0
Gorky Suquinagua On BEST ANSWER

Maybe you need to include the Schema decorator above the Application class in your application.schema.ts file.

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';

@Schema()
export class Application {
}
0
Alex Choi On

I wrote a code and push to github. In my case, I got an Error. So I fix it and working well. I use my mongodb Atlas to simulate your code

I only add 'app.id=app._id'(/src/events/events.service.ts 59) part.

Below is the result. enter image description here

You could check the github link. https://github.com/Alex-Choi0/stackoverflow_problams1