我有一个看起来像这样的模型:
mongoose.Schema({
username: String,
posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
});
我有一个要传递 ObjectID 的端点:
app.delete('/post', function(req, res) {
User.findOne({ _id: req.user._id}, function(err, result) {
result.pull({ _id: req.body.post_id });
});
});
感觉它应该可以工作,但我收到了这个错误:
CastError:转换为 ObjectId 值“[object Object]”失败
我做错了什么?
最佳答案
如果你想从数组中删除一个元素,使用这个
User
.update(
{_id: req.user._id},
{ $pull: {posts: req.body.post_id } }
)
.then( err => {
...
});
这里是 documentation
关于node.js - Mongoose : Remove object from array based on ID (Cast Error),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35973960/