0

I have this model

student: {
   package:{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Package',
   },
   history: [
    {
      package: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Package',
      },
      orderDate: {
        type: Date,
        default: new Date().toLocaleDateString('id'),
      },
      Status: {
        type: String,
        default: 'Pending',
      },
    },
  ],
}

What I want to do is that I want to update Student.package and Student.history in 1 pass

I create this method in my model

StudentSchema.methods.updatePackage= function(idPackage) {
  this.package = idPackage;
  return this.save();
};

StudentSchema.methods.updateHistory= function(idPackage) {
  this.history.push(idPackage);
  return this.save();
};

and I'm trying to do something like this in my controller

buyPack: async (req, res, next) => {
    try {
      let dataStudent = await Student.findById('5b83443040e3751bb4e32a21');
      await dataStudent.updatePackage(req.body);
      await dataStudent.updateHistory(req.body);
      return res.json(dataStudent);
    } catch (err) {
      console.log(err);
      next(err);
    }
  },

I think the first and second methods are wrong, but I have tried to figure it out in almost half of day, but still no luck. What is the best way to achieve my goals?

Do I make my model wrong? or do the methods I created are wrong?

1 Answer 1

1

Mongoose model rename with plural .. and you refer with singular with "S", "Package" change it to "Packages"

Sign up to request clarification or add additional context in comments.

5 Comments

which one? both?
yes both, first check the collection name is plural
oke now I got another error saying ValidationError: Student validation failed: package: Cast to ObjectID failed for value "{ package: '5b76586b4d4b86370c10e45e' }" at path "package"
oh the first problem is solved, I just need to do something like idPackage.package, but how about the 2nd problems? am i doing it correctly? updateHistory
one more thing . i notice .. req.body is Object , you have to pass Mongoose.ObjectId(idPackage.package)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.