通过Mongoose中给定的_id in从数组中删除对象

时间:2014-05-21 22:04:43

标签: node.js mongodb mongoose mongoid crud

在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) {
        // ...
    });

它不起作用。我做错了什么?

1 个答案:

答案 0 :(得分:4)

引自SERVER-2016

  

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

所以只需在没有$elemMatch的情况下执行您的查询:

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