Deleting Documents
Deleting a document removes it from the collection for good. Mongoose offers helpers that find a document and remove it in one step.
Remove one note
The note titled 'Read a book' is removed.
await Note.deleteOne({ title: 'Read a book' });Remove every match
Every finished note is removed at once.
await Note.deleteMany({ done: true });Example
import mongoose from 'mongoose';
const noteSchema = new mongoose.Schema({
title: String,
done: Boolean,
priority: Number
});
const Note = mongoose.model('Note', noteSchema);
await mongoose.connect('mongodb://localhost:27017/notes');
await Note.create({ title: 'Buy milk', done: false, priority: 1 });
await Note.create({ title: 'Ship MERN', done: true, priority: 3 });
await Note.create({ title: 'Read a book', done: false, priority: 2 });
const result = await Note.deleteOne({ title: 'Read a book' });
console.log(result.deletedCount);
const notes = await Note.find();
console.log(notes.map(n => n.title));
await mongoose.disconnect();Key points
- deleteOne removes the first document that matches a filter.
- deleteMany removes every document that matches a filter.
- Both helpers return a result that reports how many documents were removed.
- A filter that matches nothing removes nothing and reports zero.
- findOneAndDelete removes a document and returns it in one step.
In this example, three notes are saved first. deleteOne removes the note titled 'Read a book'. The printed count of 1 shows one document removed, and the printed list shows the two notes that remain.
Note
A deleted document cannot be brought back, so check the filter first.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which helper removes every document that matches a filter?