简体   繁体   中英

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.

I'm using 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.

The pull syntax you have is wrong. $pull takes an array, which in your case is "members".

You want this update instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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