Saving Documents
Saving a document stores a new record in the database. The save method writes the document to its collection.
Make a note
This line makes a new note in code.
const note = new Note({ title: 'Buy milk', done: false });Save it
This line writes the note to the database.
await note.save();The saved title
This line prints the title of the saved note.
console.log(note.title);Example
import mongoose from 'mongoose';
await mongoose.connect('mongodb://localhost:27017/notes');
const noteSchema = new mongoose.Schema({
title: String,
done: Boolean
});
const Note = mongoose.model('Note', noteSchema);
const first = new Note({ title: 'Buy milk', done: false });
await first.save();
console.log(first.title);
const second = new Note({ title: 'Ship MERN', done: true });
await second.save();
console.log(second.title);
const third = new Note({ title: 'Read a book', done: false });
await third.save();
console.log(third.title);
await mongoose.disconnect();Key points
- A new document starts as a plain model object in code.
- The save method sends that document to MongoDB.
- Save is async, so the code waits for it with await.
- The document keeps its title and done flag after saving.
- Each save adds one more document to the collection.
In this example, the connect line opens the link to the notes database. Each block makes one note and saves it. The print after each save shows the title of the note just saved. The output lists the three notes in the order they were saved. The disconnect line closes the link.
Note
A saved document stays in the database after the script ends.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which method writes a new document to the database?