(node:15893) DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead

Viewed 10533

I'm developing a backend for REST API. It uses MongoDB as a database. I am using mongodb v: ^5.3.3.

I would like to remove a collection of items, upon API request, but received the above error message:

DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead

How do I completely drop the collection?

4 Answers

Instead of: Model.remove({}); Use: Model.deleteMany({});

What worked for me when I wanted to drop a specific collection is:

mongoose.connection.dropCollection(specificCollection.name)
// or you could use the collection's name exactly such as 'user'

The mongoose.connection.dropCollection() method takes in the exact name for a collection which you probably defined when you made the schema.

Probably, the specific model you have defined somewhere in your code is something like:

mongoose.model('User', UserSchema)

Note that it is case insensitive, 'User' is the same as 'user'.

Use deleteOne or deleteMany accordingly. I have used deleteOne() instead of remove() function to delete items from delete api from mongodb collections. It worked for me.

app.delete('/todo/:item', function(req, res){   
  Todo.find({item: req.params.item.replace(/\-/g, " ")}).deleteOne(function(err, data){
    if(err) throw err;
      res.json(data);   
  }); 
});

This problem occurs in new versions of mongoose, if you want to use Model.remove() method you should change the current mongoose version to "mongoose": "^5.10.14" or lower. Readmore information about it at https://mongoosejs.com/docs/deprecations.html

Related