Mongoose:根据ID从数组中删除对象(Cast Error)

我有一个看起来像这样的模型:

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: Cast to ObjectId failed for value "[object Object]"

我究竟做错了什么?

如果你想从数组中删除一个元素,使用这个

 User .update( {_id: req.user._id}, { $pull: {posts: req.body.post_id } } ) .then( err => { ... }); 

这里的文件

 This is because when you are running user findOne query it returns an object to you.(the findOne function returns only one object) User.findOne({ _id: req.user._id}, function(err, result) { /// result is an object result.pull({ _id: req.body.post_id }); }); and what is result.pull you are trying to pull an element from object this is the wrong way to do do like this delete result._id; and if you want more elements from user query in from of array you can use User.find({ _id: req.user._id}, function(err, result) { // result.slice for slice you can see this http://stackoverflow.com/questions/3396088/how-do-i-remove-an-object-from-an-array-with-javascript }); then you can do slice on array of object 

为了在集合中使用id进行研究,您需要创build一个新的ObjectId,然后将id传递给它。

 app.delete('/post', function(req, res) { User.findOne({ _id: _id: ObjectId (req.user._id)}, function(err, result) { result.pull({ _id: ObjectId (req.body.post_id) }); }); });