Reading Documents
Reading documents means fetching records back from the database. The find method returns every document in a collection.
Find every note
This line fetches every document in the collection.
const notes = await Note.find();Print the titles
This line prints only the title of each note.
console.log(notes.map(n => n.title));The first title
This line prints the title of the first note.
console.log(notes[0].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);
await new Note({ title: 'Buy milk', done: false }).save();
await new Note({ title: 'Ship MERN', done: true }).save();
await new Note({ title: 'Read a book', done: false }).save();
const notes = await Note.find();
console.log(notes.map(n => n.title));
await mongoose.disconnect();Key points
- The find method asks the collection for its documents.
- Find is async, so the code waits for it with await.
- Find returns an array of documents.
- Sort orders the documents before they are printed.
- Mapping the array prints only the titles, not the whole documents.
In this example, the connect line opens the link to the notes database. The three save lines store the three notes. The find line fetches every document, sorted by title. The print shows only the titles, in sorted order. The disconnect line closes the link.
Note
Always sort a printed list. Sorted output stays the same on every run.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does Note.find() return?