简体   繁体   中英

Unable to remove element from Array in Mongoose

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
});

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM