Title. I noticed that there are two (maybe more) ways to remove a specific object from an array in a document. Example schema:
var diveSchema = new Schema({
//irrelevant fields
divers: [{
user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
meetingLocation: { type: String, enum: ['carpool', 'onSite'], required: true },
dives: Number,
exercise: { type: Schema.Types.ObjectId, ref: 'Exercise' },
}]
});
For example, here they used $pull syntax
Dive.update({ _id: diveId }, { "$pull": { "divers": { "user": userIdToRemove } }}, { safe: true, multi:true }, function(err, obj) {
//do something smart
});
to remove a matching object. But sometimes, this is used
let dive = await Dive.findById(diveId)
dive.drivers = dive.drivers.filter(driver => driver.user.toString() !=== userIdToRemove);
await dive.save();
Which one is better and recommended?