{
"_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){
})
I want to find the nested id of item in the nested array trade
and delete all items where trade.myCar._id = req.body.myCar._id
. I want to remove the item which contains the object selectedCar
and myCar
Use "new" to return the modified document and the argument to $pull
in the "inner" name only:
User.findOneAndUpdate(
{ "trade.myCar._id" : req.body.myCar._id },
{ "$pull": {
"trade.$": { "myCar._id" : req.body.myCar._id }
}},
{ "new": true },
function(err,trade) {
}
})
Note: This does remove the entire array element as you ask. To just remove "myCar" then use $unset
:
User.findOneAndUpdate(
{ "trade.myCar._id": req.body.myCar._id },
{ "$unset": { "trade.$.myCar": "" }},
{ "new": true },
function(err,trade) {
}
})
In that case the array element is intact, but that key is gone from that element.
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.