Mongoose - remove multiple documents in one function call

62,518

Solution 1

I believe what youre looking for is the $in operator:

Site.deleteMany({ userUID: uid, id: { $in: [10, 2, 3, 5]}}, function(err) {})

Documentation here: https://docs.mongodb.com/manual/reference/operator/query/in/

Solution 2

You can also use.

Site.remove({ userUID: uid, id: { $in: [10, 2, 3, 5]}}, function(err, response) {});

Solution 3

I had to change id to _id for it to work:

Site.deleteMany({ _id: [1, 2, 3] });

This happens if no id is defined and the default one is used instead:

"Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor." mongoose docs

Solution 4

Yes, $in is a perfect solution :

Site.deleteMany({ userUID: uid, id: { $in: [10, 2, 3, 5] } }, function(err) {})

Share:
62,518
Maciej Krawczyk
Author by

Maciej Krawczyk

Working on something...

Updated on July 09, 2022

Comments

  • Maciej Krawczyk
    Maciej Krawczyk almost 2 years

    In documentation there's deleteMany() method

    Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, function (err) {});
    

    I want to remove multiple documents that have one common property and the other property vary. Something like this:

    Site.deleteMany({ userUID: uid, id: [10, 2, 3, 5]}, function(err) {}

    What would be the proper syntax for this?

  • Darin Kolev
    Darin Kolev over 5 years
    it is deprecated in Mongoose 5.x, deleteMany should be used there
  • Ramazan Chasygov
    Ramazan Chasygov almost 5 years
    you can omit $in, just id: [10, 2, 3, 5]