Home > database >  How do I get MongoDB to pull items from an array using bulkWrite?
How do I get MongoDB to pull items from an array using bulkWrite?

Time:06-18

Here's my schema:

const mySchema = mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  words_collection: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Word',
  }],
})

And here is my code in my controller:

(passing an array of ref IDs like ['someId', 'anotherId'] called wordsRemoved to my async function)
...
await MySchema.bulkWrite([
  {
    'updateOne': {
      'filter': { '_id': _id },
      'update': {
        $pull: { 'words_collection': wordsRemoved }
      }
    }
  }
]);

No errors are thrown, but no IDs are being pulled. I need to use bulkWrite, specifically, because I also need to add elements to 'words_collection' at the same time.

CodePudding user response:

I figured it out. It was very simple. I need to use $pullAll instead of $pull.

  • Related