简体   繁体   English

如何用猫鼬从数字数组中删除对象

[英]How to remove object from numeric array with mongoose

I got this kind of document 我有这种文件

{
    "_id" : "5339be1d9a703ab8708b45675339bed39aac7",
    "description" : "data",
    "name" : "data",
    "members" : [ 
        {
            "user" : {
                "$ref" : "users",
                "$id" : ObjectId("5339be1d9a703ab8708b4567"),
                "$db" : "someDb"
            },
            "type" : "Principal"
        }, 
        {
            "user" : {
                "$ref" : "users",
                "$id" : ObjectId("5339c0c59a703a5d1f8b4569"),
                "$db" : "someDb"
            },
            "type" : "Regular"
        }
    ],
    "owner" : "5339be1d9a703ab8708b4567",
}

And I'm trying to pull an element from the array members, finding it by the $id in user object. 我正在尝试从数组成员中拉出一个元素,并通过用户对象中的$ id找到它。

I'm using Mongoose ODM. 我正在使用Mongoose ODM。

This is my function: 这是我的功能:

>  var conditions = {"_id" : data.guildId},
>      update = 
>      {
>         $pull : 
>         {
>           'members.user.$id' : new mongoose.Types.ObjectId(data.userId) 
>         }
>      };
>      var options = {upsert:false};
> 
>     Guild.update(conditions, update, options, leaveRoom);

There are no errors reported in my node js server or in the mongo log file, but the document remains unaffected. 我的节点js服务器或mongo日志文件中未报告任何错误,但该文档不受影响。

The pull syntax you have is wrong. 您使用的pull语法错误。 $pull takes an array, which in your case is "members". $ pull接受一个数组,在您的情况下为“成员”。

You want this update instead: 您需要此更新:

{ "$pull" : { "members" : { "user.$id" : <your-condition> } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM