The deleteMany() Function in Mongoose
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.
The deleteMany() Function in Mongoose
The deleteMany()
function is how you can delete multiple documents from a collection using Mongoose.
It takes up to two parameters:
- condition, what a document should contain to be eligible for deletion. You can omit this property to delete all documents in the model.
- options, other configurable parameters, like
session
orwriteConcern
.
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
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK