Sonaryr
Sonaryr

Reputation: 1122

How to remove Object from array using mongoose

I'm trying to remove an object from an array in a document using mongoose.

The Schema is the following:

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' },
    }]
});

a possible entry can be

{
    //irrelevant fields
    "divers": [
        {
            "_id": "012345678",
            "user": "123456789",
            "meetingLocation": "carpool",
            "exercise": "34567890",
        },
        {
            "_id": "012345679",
            "user": "123456780",
            "meetingLocation": "onSite",
            "exercise": "34567890",
        }
    ]
}

Say I want to remove the entry where user is 123456789 (note I do not know the _id at this point).

How do I do this correctly?

I tried the following:

        var diveId = "myDiveId";
        var userIdToRemove = "123456789"
        Dive.findOne({ _id: diveId }).then(function(dive) {
            dive.divers.pull({ user: userIdToRemove });
            dive.save().then(function(dive) {
                //do something smart
            });
        });

This yieled no change in the document.

I also tried

Dive.update({ _id: diveId }, { "$pull": { "divers": { "diver._id": new ObjectId(userIdToRemove) } } }, { safe: true }, function(err, obj) {
    //do something smart
});

With this I got as result that the entire divers array was emptied for the given dive.

Upvotes: 20

Views: 33408

Answers (5)

ZAFAR HUSSAIN
ZAFAR HUSSAIN

Reputation: 181

Use this with try/catch:

await Group.updateOne(
  { _id: groupId },
  { $pull: { members: {id: memberId }}}
);

Upvotes: 0

Al Imran Hossain
Al Imran Hossain

Reputation: 205

I solve this problem using this code-

 await Album.findOneAndUpdate(
    { _id: albumId },
    { $pull: { images: { _id: imageId } } },
    { safe: true, multi: false }
  );
  return res.status(200).json({ message: "Album Deleted Successfully" });

Upvotes: 6

Tazim Karim Madre
Tazim Karim Madre

Reputation: 49

Try this async code

var diveId = "myDiveId";
var userIdToRemove = "123456789"
const dive=await Dive.findOne({ _id: diveId })
await dive.divers.pull({ user: userIdToRemove });
await dive.save();

Upvotes: 0

pankaj007
pankaj007

Reputation: 95

Try this

Dive.update({ _id: diveId },{"$pull": { "drivers": {"user": "123456789"}}})

Upvotes: 0

Rahul Kumar
Rahul Kumar

Reputation: 2831

What about this?

Dive.update({ _id: diveId }, { "$pull": { "divers": { "user": userIdToRemove } }}, { safe: true, multi:true }, function(err, obj) {
    //do something smart
});

Upvotes: 39

Related Questions