Home > Net >  problem when creating one to many data in mongoose
problem when creating one to many data in mongoose

Time:10-01

so i'm creating CRUD with relation of two collections, then i got problem, i can't do push from first collection data to second collection. this is my code.

Schema

const CourseSchema = new Schema(
  {
    title: {
      type: String,
      required: true,
    },
    desc: String,
    price: Number,
    video: String,
    category: String,
    status: Number,
    lessons: [
      {
        type: Schema.Types.ObjectId,
        ref: "Lessons",
      },
    ],
  },
  {
    timestamps: true,
  }
);

const course = mongoose.model("Courses", CourseSchema);


const LessonSchema = new Schema(
  {
    title: {
      type: String,
      required: true,
    },
    desc: String,
    video: String,
    status: Number,
   
  },
  { timestamps: true }
);

const Lessons = mongoose.model("Lessons", LessonSchema);

code to do data push

Lessons.create(req.body)
    .then((data) => {
      res.status(200).send({
        status: 200,
        message: "Successfully Create Lessons",
        data: data,
      });
      Course.findByIdAndUpdate(
        courseId,
        { $push: { lessons: data._id } },
        { safe: true, upsert: true, new: true }
      );
    })

is there any solution for my problem? please help me, i'm just learning about one to many relation in nodejs using mongoose

CodePudding user response:

You need a callback function to make it works.

Lessons.create(req.body)
.then((data) => {
  res.status(200).send({
    status: 200,
    message: "Successfully Create Lessons",
    data: data,
  });
  course.findByIdAndUpdate(
    courseId,
    { $push: { lessons: data } },
    { safe: true, upsert: true, new: true },
    function (err, newdoc) { // callback function
        if (err) {
           console.log(err);
        } else {
           console.log("completed");
        }
    }
  );
})
  • Related