Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 435
Sonaryr Avatar asked Nov 14 '16 12:11

Sonaryr


People also ask

How to pull an object from an array MongoDB?

To remove object from array with MongoDB, we can use the $pull operator. db. mycollection. update({ '_id': ObjectId("5150a1199fac0e6910000002") }, { $pull: { items: { id: 23 } } }, false, true, );

How do you delete an item from MongoDB using mongoose?

We can delete documents using mongoose with the help of different methods like Model. deleteOne(), Model. findOneAndDelete(), Model. deleteMany(), and Model.

What is the mongoose command used to delete an item?

There are a few different ways to perform delete operations in Mongoose: deleteOne() to delete a single document, deleteMany() to delete multiple documents and remove() to delete one or multiple documents.

What is $Push in mongoose?

$push. The $push operator appends a specified value to an array. The $push operator has the form: { $push: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.


2 Answers

What about this?

Dive.update({ _id: diveId }, { "$pull": { "divers": { "user": userIdToRemove } }}, { safe: true, multi:true }, function(err, obj) {
    //do something smart
});
like image 155
Rahul Kumar Avatar answered Oct 09 '22 09:10

Rahul Kumar


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" });
like image 43
Al Imran Hossain Avatar answered Oct 09 '22 10:10

Al Imran Hossain