🎓 A1Learner
🔍
0 of 50 lessons completed

Finding by Id

Finding by id fetches one document using its unique identifier. Every document gets an _id when it is saved, and findById looks it up directly.

Read the id from a document

findOne reads the note, and its _id sits on the result.

const first = await Note.findOne({ title: 'Buy milk' });

Look the document up

findById fetches the same note by its id.

const note = await Note.findById(first._id);

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 },
  { title: 'Ship MERN', done: true, priority: 3 },
  { title: 'Read a book', done: false, priority: 2 }
]);

const first = await Note.findOne({ title: 'Buy milk' });
const note = await Note.findById(first._id);
console.log(note.title);

await mongoose.disconnect();

Key points

  • Every document carries an _id field that MongoDB sets when it is saved.
  • findById takes one id value and returns the matching document.
  • An id that matches nothing returns null, not an error.
  • The id is stored on the document, so it can be read from a found document.
  • Finding by id is direct, since the id is indexed by default.

In this example, three notes are saved first. findOne reads the note titled 'Buy milk' so its _id can be used. findById then fetches the same note by that id, and the printed title shows the lookup worked.

Note

An _id looks like a long string of letters and digits.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does findById return when no document has that id?