1

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"
        }
    }
}
2
  • 1
    Remove $elemMatch. It should be { $pull: { pref: { _id: mongoose.Types.ObjectId(pid) } } } Commented Jan 1, 2019 at 5:35
  • ...well...That's embarrassing. Thx - that worked. Commented Jan 1, 2019 at 5:36

1 Answer 1

1

$elemMatch is an query and projection operator. There is nothing to do it with the update operators.

So instead try to do something like this

User.update(
  { "_id": mongoose.Types.ObjectId(uid) },
  { "$pull": { "pref": { "_id": mongoose.Types.ObjectId(pid) } } }
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.