通过在Mongoose中给定_id,从数组中删除对象

在Mongoose模型中用户给出的文档如下所示:

> db.users.find().pretty() { /* ... */ "events" : [ { "_id" : ObjectId("537bb2faf87f9a552c3219ea"), "message" : "Foo" }, { "_id" : ObjectId("537bb436c3b9a1aa2db71b7c"), "message" : "Bar" }, { "_id" : ObjectId("537bb4ab2cc503e52e24d145"), "message" : "Biz" }, { "_id" : ObjectId("537bb4d02cc503e52e24d146"), "message" : "Pop" } ] 

}

某些函数将event _id作为参数,并且必须从MongoDB中删除响应此_id的对象。 我试过了:

 User .findByIdAndUpdate(req.user._id, { $pull: {events: { $elemMatch: {_id: _eventId} //_eventId is string representation of event ID }} }, function(err) { // ... }); 

它不工作。 我究竟做错了什么?

从SERVER-2016引用:

$ pull的参数已经应用到目标数组的每个元素,所以在更新上下文中使用$ elemMatch是多余的。

所以只需执行您的查询,而不需要$elemMatch

 User .findByIdAndUpdate(req.user._id, { $pull: {events: { _id: _eventId //_eventId is string representation of event ID }} }, function(err) { // ... });