1

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?

1 Answer 1

1

The first one seems to be better, because there is one db access, the second one has two db access (one for findById and one for save)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.