Reputation: 10261
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
});
Upvotes: 0
Views: 115
Reputation: 48366
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.
Upvotes: 1