如果找到嵌套id,如何删除子文档中的数组项

时间:2015-07-14 07:18:27

标签: javascript mongodb mongoose

{
    "_id" : ObjectId("55a4b23636e6ba35079eb497"),
    "userName" : "David",
    "email" : "david@gmail.com",
    "image" : "https://lh5.googleusercontent.com/-ivBeNFeatn4/AAAAAAAAAAI/AAAAAAAABkk/aa86ghW9VRg/photo.jpg?sz=50",
    "trade" : [ 
        {
            "selectedCar" : {
                "model" : "Mikecar",
                "year" : 77878,
                "condition" : "hkjhkj",
                "color" : "hkjhjkhjkhjk",
                "_id" : "55a4b22d36e6ba35079eb496",
                "imageUrl" : "http://cliparts.co/cliparts/Big/Kkz/BigKkzggT.png",
                "userName" : "josh Smith",
                "email" : "josh@gmail.com"
            },
            "myCar" : {
                "model" : "Son90098",
                "year" : 879,
                "condition" : "kjhjkhkhj",
                "color" : "khjhjkhjk",
                "_id" : "55a4b24036e6ba35079eb498",
                "imageUrl" : "http://cliparts.co/cliparts/Big/Kkz/BigKkzggT.png"
            },
            "myEmail" : "david@gmail.com"
        },
    "__v" : 2
}



User.findOneAndUpdate({'trade.myCar._id' : req.body.myCar._id }, {$pull: {'trade.$': {'trade.myCar._id' : req.body.myCar._id }}}, function(err,trade){
})

我想在嵌套数组trade中找到item的嵌套id,并删除trade.myCar._id = req.body.myCar._id中的所有项目。我想删除包含对象selectedCarmyCar

的项目

1 个答案:

答案 0 :(得分:0)

使用“new”仅将修改后的文档和参数返回到“内部”名称中的$pull

User.findOneAndUpdate(
   { "trade.myCar._id" : req.body.myCar._id }, 
   { "$pull": {
       "trade.$": { "myCar._id" : req.body.myCar._id }
   }},
   { "new": true },
   function(err,trade) {

   }
})

注意:此 会根据您的要求删除整个数组元素。要删除“myCar”,请使用$unset

User.findOneAndUpdate(
   { "trade.myCar._id": req.body.myCar._id }, 
   { "$unset": { "trade.$.myCar": "" }},
   { "new": true },
   function(err,trade) {

   }
})

在这种情况下,数组元素是完整的,但该键已从该元素中删除。