MahanTp
MahanTp

Reputation: 744

Remove from array of objectId using update mongoDB

I have a model named courier, it has an array named order and orders has some ObjectIds of model order, how can I remove an element from orders array using update or something else ?

(for example removing an order with specific id)

Here is my model:

courier:

var courierSchema = new Schema({
    name: { type: String },
    orders:[{type:Schema.Types.ObjectId,ref:'order'}],
});

I tried this code but it fails :

courier.update({
                   name: 'Mahan'
               }, {
                    $pull : {
                      orders: {
                          _id: order._id
                      }
                  }
                }, (err, count, obj) => {
                    if(err) {
                        console.log(err);
                        return handleError(err, reply);
                    }
                    console.log(count);
                });

Is there any way to do this not using find, remove and then save ?

Upvotes: 1

Views: 1218

Answers (1)

Ulug Toprak
Ulug Toprak

Reputation: 1222

This would be the most efficient format to achieve what you are trying to do

db.collection.update({<cond to identify document}, {$pull: {'orders': {'id': <id>}}} )

Upvotes: 1

Related Questions