2015-10-04 85 views
0

我有一個問題,如果我嘗試通過ObjectId更新文檔,我得到一個MongooseError.CastError。任何幫助?Mongoose通過ObjectId更新文檔

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') 
}) 
+0

你也可以使用'findByIdAndUpdate'方法 –

回答

1

讓Mongoose根據定義的模式爲您進行施法。

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