5

The deleteMany() Function in Mongoose

 2 years ago
source link: https://masteringjs.io/tutorials/mongoose/deletemany
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

The deleteMany() Function in Mongoose

Nov 5, 2021

The deleteMany() function is how you can delete multiple documents from a collection using Mongoose. It takes up to two parameters:

  1. condition, what a document should contain to be eligible for deletion. You can omit this property to delete all documents in the model.
  2. options, other configurable parameters, like session or writeConcern.
const testSchema = new mongoose.Schema({
    name: String
});
const Test = mongoose.model('Test', testSchema);

await Test.create({name: 'Test Testerson'});
await Test.create({name: 'Test Testerson'});
await Test.create({name: 'Test Testerson'});
await Test.create({name: 'Masteringjs'});
await Test.create({name: 'MeanIT'});

await Test.deleteMany({name: 'Test Testerson'});
await Test.find(); // will return Masteringjs and MeanIT documents

Return Value

Once the documents are deleted, it will return an object with a property, deletedCount, containing the number of documents deleted.

const testSchema = new mongoose.Schema({
    name: String
});
const Test = mongoose.model('Test', testSchema);

await Test.create({name: 'Test Testerson'});
await Test.create({name: 'Test Testerson'});
await Test.create({name: 'Test Testerson'});
await Test.create({name: 'Masteringjs'});
await Test.create({name: 'MeanIT'});

await Test.deleteMany({name: 'Test Testerson'}); // {deletedCount: 3}

Want to become your team's MongoDB expert? "Mastering Mongoose" distills 8 years of hard-earned lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need to know to build production-ready full-stack apps with Node.js and MongoDB in a few days. Get your copy!


More Mongoose Tutorials


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK