Chris Paterson
Chris Paterson

Reputation: 193

How can I remove an object from an array?

I want to remove an object from an array. Here is the schema I'm working with:

event: {
    invitees: {
        users : [{
            user: {
                type: String,
                ref: 'User'
            },
        }],
    }
}

The query I'm using is listed below, but it isn't working. Basically, nothing happens when I run this script.

Event.update(
        {"_id": req.params.event_id},
        {"$pull": {"invitees.users.user": req.params.user_id}},
        {safe: true, upsert: true},
        function (err, data) {
            if (err) {
                console.log(err);
            }
            return res.json({ success: true });
        }
    );

What am I doing wrong?

Upvotes: 0

Views: 48

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

The field of the $pull operator identifies the array to pull the elements from that match its query.

So your update should look like this instead:

Event.update(
    {"_id": req.params.event_id},
    // { $pull: { <array field>: <query> } }
    {"$pull": {"invitees.users": {"user": req.params.user_id}}},
    {safe: true, upsert: true},
    function (err, data) {
        if (err) {
            console.log(err);
        }
        return res.json({ success: true });
    }
);

Upvotes: 1

Related Questions