I have a collection that has an array of objects - each with a UNIQUE ID - I want to be able to delete an item from the array - or a specific record. I have code that doesn't error - yet it does not remove the object from the array.
COLLECTION STRUCTURE
_id:
,username:
,prefs: [
_id:
,title:
]
DATA LOOKS LIKE
_id: 5a...46,
username: "bobsmith",
prefs: [
{
_id: 5...a,
composition_title: "blah 1"
}
,{
_id: 5 c...2,
composition_title: "blah 2"
}
,{
_id: 5 c...c,
composition_title: "blah 3"
}
]
CODE:
module.exports.removeUserPref = function (uid, pid, callback) {
User.update(
{
'_id': mongoose.Types.ObjectId(uid)
},
{
$pull: { pref: { $elemMatch: { _id: mongoose.Types.ObjectId(pid) } } }
}
, callback);
}
I know the User ID I am passing is correct and the Pref Id I am passing IS in the array - but My response is : "nModified": 0 and no deleted item
{
"n": 1,
"nModified": 0,
"opTime": {
"ts": "6641391849170796549",
"t": 4
},
"electionId": "7fffffff0000000000000004",
"ok": 1,
"operationTime": "6641391849170796549",
"$clusterTime": {
"clusterTime": "6641391849170796549",
"signature": {
"hash": "sBXjaw1nw99+cfMIMVNq5KtCpt8=",
"keyId": "6596828466803376130"
}
}
}
$elemMatch. It should be{ $pull: { pref: { _id: mongoose.Types.ObjectId(pid) } } }