sawa
sawa

Reputation: 2050

Mongoose updating a document by ObjectId

I have an issue where if I try to update a document by ObjectId, I get a MongooseError.CastError. Any help?

var comment = new Comment({
    contents: 'contents'
})

console.log(typeof req.body.postId) // 'string'

Post.update({_id: db.Types.ObjectId(req.body.postId)}, { // 'cast error'
    commentsId: {$push: comment._id}
}, function(err, numAffected, res){
    if (err) { return next(err)}
    console.log('success')
})

Upvotes: 1

Views: 4172

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

Let Mongoose do the casting for you based on the defined schema.

Post.update({_id: req.body.postId}, {commentsId: {$push: comment._id}}, ...

Upvotes: 3

Related Questions