Clayton Shaver Clayton Shaver - 6 months ago 43
Node.js Question

mongoose findByIdAndUpdate not modifying model and not returning error

I have a mongoose model called Message, when that model is created I want to save the Message Id to an array in another model called User. However when the findByIdAndUpdate method is called its not modifying the user model nor is it returning an error message. I've checked that I'm using the correct User id and the Message id is also valid. Any thoughts as to why mongoose is behaving this way?

Message.post('save', function addMessageToUser(doc) {
User.findByIdAndUpdate(doc.userID, {
$push: {
messages: {
$each: [doc._id],
$sort: { createdAt: 1 },
$slice: -1000,
},
},
}, {
new: true,
}, (response, error) => {
console.log(response);
console.log(error);
})
});

Answer

After trying the same command in the mongo cli I found that doc.userID wasn't being cast to and ObjectId. Instead I used mongoose.Type.Object(doc.userID) to cast the string to a ObjectId before executing the query.

Message.post('save', function addMessageToUser(doc) {
User.update({
    "_id": mongoose.Types.ObjectId(doc.userID),
  }, {
    $push: {
      messages: {
        $each: [doc._id],
        $sort: { createdAt: 1 },
        $slice: -1000,
      },
    },
  })
}
Comments