0

I am trying to remove an element through its _id from an array model in mongoose. The same technique is working elsewhere in my code, but here it fails to remove the element. After hours of trying to change various parts of it, I am finally posting it here because maybe my lack of sleep is the main reason. Can someone find out what i am doing wrong?

ABC.findOne({
    'user': new ObjectId(req.decoded._id),
    'activity.ride': new ObjectId(id)
}, {
    'activity.$': 1
}, function(err, doc) {

    if (doc !== null) {
        for (var j = 0; j < doc.activity.length; j++) {
            var request = JSON.parse(JSON.stringify(doc.activity[j]));
            doc.activity.remove(request._id);
            doc.save();
        }
    }
});

This is the model:

var activityItem = mongoose.Schema({
    timestampValue: Number,
    xabc: String,
    full: Boolean,
    comp: Boolean
});

var ABC = mongoose.Schema({
    activity: [activityItem],
    user: {
        type: mongoose.Schema.ObjectId,
        ref: 'User'
    },
    username: String
});

1 Answer 1

1

The $pull operator removes from an existing array all instances of a value or values that match a specified condition. And to remove element from array through findOneAndUpdate

ABC.findOneAndUpdate({'user': new ObjectId(req.decoded._id)},
                    {$pull: {activity: {_id: request._id}}},
                    {new: true},
                    function(err, a) {
                        if (err)
                            console.log(err);
                        else
                            console.log(a);
                    });

BTW, I did not find ride in the activityItem schema, so I remove the ride from query condition.

Sign up to request clarification or add additional context in comments.

1 Comment

@amit, sorry for previous mistake, I have updated my answer, please try it again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.