mogoose is obsoluting the data into database whereas after JSON.parse(JSON.stringify()) work

Viewed 43

I am working with NestJS for REST APIs where inside a POST request I am retrieving some nested populated data from a collection document and creating its duplicate to embed into other collection before creating. few are the observations.

  1. mongoose just saves the _id key and obsolute all other data.
  2. When I populate data with deselected _id, mongoose save null.
  3. If I perform 2. observation and before saving JSON.parse(JSON.stringify(populated_data)) It works fine.

I don't want to JSON.parse(JSON.stringify()) for each request as it may not be an efficient way to do so(may consume CPU cycles).

Please help me out. Here's some part of the code

async createProjects(
    @Req() req: any,
    @Res() response: any,
    @Body() project: Project & { services: ObjectId[] },
) {
    let { services, service: _service, ...projectData } = project;
    Promise.all(
        project.services.map(async (service: string | ObjectId) => {
            const { taskGroups = [] }: any =
            (await this.servicesService.populateTaskFromService(service, {
              path: 'taskGroups',
              select: '-_id',
              populate: {
                path: 'tasks',
                select: '-_id',
                populate: {
                  path: 'form',
                  select: '-_id',
                },
              },
            })) || {};
          const _project = {
            ...projectData,
            service,
            taskGroups: JSON.parse(JSON.stringify(taskGroups)),
          };
          projects.push(_project);
          return _project;
        })
    ).then((projectToCreate)=>{
        return this.projectService
        .createMany(projectsToCreate) // in service this.projectModel.insertMany(projectsToCreate) is used
        .then((createdProjects)=>res.status(200).json(createdProjects))
        .catch(...)
    }).catch(...);
}

Project Schema:

export type ProjectDocument = Project & Document;

@Schema({
  strict: false,
  timestamps: true,
})
export class Project extends BaseEntity {
  @ObjectIdColumn({ primary: true })
  _id: ObjectID;

  @Prop({ type: 'string', enum: ProjectStatus, default: ProjectStatus.DRAFT })
  status: ProjectStatus;

  @Prop({ type: Number, min: 1970, default: new Date().getFullYear() })
  year: number;

  @Prop({ type: Date, default: new Date() })
  date: Date;

  @Prop({ required: true, index: true, unique: true })
  projectNumber: number;

  @Prop({ required: true, default: new Date() })
  createdAt: Date;

  @Prop({
    required: true,
    default: null,
    type: mongoose.Schema.Types.ObjectId,
    ref: Service.name,
  })
  @Type(() => Service)
  service: mongoose.Schema.Types.ObjectId;

  @Prop({
    default: null,
    type: mongoose.Schema.Types.ObjectId,
    ref: 'FormsData',
  })
  @Type(() => FormsData)
  formData: mongoose.Schema.Types.ObjectId;

  @Prop({
    required: true,
    default: null,
    type: mongoose.Schema.Types.ObjectId,
    ref: User.name,
  })
  @Type(() => User)
  userId: mongoose.Schema.Types.ObjectId;

  @Prop({ type: [mongoose.Schema.Types.Mixed] })
  taskGroups: mongoose.Schema.Types.Mixed[];
}

export const ProjectSchema = SchemaFactory.createForClass(Project);
0 Answers
Related