Updating Documents
Updating a document changes its stored fields without replacing the whole document. Mongoose offers helpers that find a document and change it in one step.
Change one field
The note titled 'Buy milk' is marked as done.
await Note.updateOne({ title: 'Buy milk' }, { done: true });Read the changed document
The option new: true returns the document after the change.
const note = await Note.findOneAndUpdate({ title: 'Buy milk' }, { done: true }, { new: true });Change many at once
Every unfinished note gets priority 1.
await Note.updateMany({ done: false }, { priority: 1 });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.updateOne({ title: 'Buy milk' }, { done: true });
console.log(result.modifiedCount);
const notes = await Note.find();
console.log(notes.map(n => `${n.title}: ${n.done}`));
await mongoose.disconnect();Key points
- updateOne changes the first document that matches a filter.
- The filter picks which documents change, and the second part gives the new values.
- updateOne returns a result that reports how many documents changed.
- findOneAndUpdate returns the changed document itself.
- By default findOneAndUpdate returns the document before the change.
In this example, three notes are saved first. updateOne finds the note titled 'Buy milk' and sets done to true. The printed count of 1 shows one document changed. The printed list shows the new done value for each note.
Note
An update changes only the fields named in the update.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does updateOne return?