Search code examples
mongodbmongoosemongodb-querymongoose-schema

How to remove an ObjectId from a ref array in a mongo schema?


I have a schema like this:

  var TestSchema = new Schema({
     name: String,
     ex: String,
     data:  [{type: Schema.ObjectId, ref: 'Data'}]
  });
  var Test = mongoose.model("Test", TestSchema);

and it appears like this in RoboT:

enter image description here

what i want to do is to delete a data by its ID. i am doing this:

Test.update({}, {$pull: {data: idD }}, function(err, test) {
    if (err) {
        res.send(err);
    }
    res.send({
        success: true
    })
});

where idD is the Data ID i want to delete. Before this i am doing just a simple

Data.deleteOne({_id: idD}, function...

and it works properly, but if i refresh the DB, my data with the idD is still present in the data array in Test Schema. i have also tried:

Test.update({}, {$pull: {data: {_id:idD }},
Test.update({}, {$pull: {data: {_id: mongoose.Types.ObjectId(idD)}}},

but nothing works.


Solution

  • You have to use multi: true when you are updating multiple documents.

     Test.update({}, {$pull: {data: idD },{multi: true}, function(err, test) {
            if (err) {
                res.send(err);
            }
            res.send({
                success: true
            })
        });