0
0
MongodbHow-ToBeginner · 3 min read

How to Use findById in Mongoose: Syntax and Examples

In Mongoose, use Model.findById(id) to find a document by its unique _id. It returns a promise that resolves to the document if found or null if not.
📐

Syntax

The findById method is called on a Mongoose model and takes the document's _id as its argument. It returns a promise that resolves to the matching document or null if no document is found.

  • Model: Your Mongoose model (e.g., User).
  • id: The unique identifier of the document, usually a string or ObjectId.
javascript
Model.findById(id)
  .then(doc => {
    // doc is the found document or null
  })
  .catch(err => {
    // handle error
  })
💻

Example

This example shows how to connect to MongoDB, define a simple User model, and use findById to find a user by their _id. It prints the user document if found or a message if not.

javascript
const mongoose = require('mongoose');

async function run() {
  await mongoose.connect('mongodb://localhost:27017/testdb');

  const userSchema = new mongoose.Schema({
    name: String,
    email: String
  });

  const User = mongoose.model('User', userSchema);

  // Example _id to search for (replace with a valid ObjectId string)
  const id = '64a1f0c2f1d2b3a4c5d6e7f8';

  try {
    const user = await User.findById(id);
    if (user) {
      console.log('User found:', user);
    } else {
      console.log('No user found with that id.');
    }
  } catch (error) {
    console.error('Error finding user:', error);
  } finally {
    await mongoose.disconnect();
  }
}

run();
Output
No user found with that id.
⚠️

Common Pitfalls

  • Passing an invalid id: If the id is not a valid ObjectId string, Mongoose throws a CastError.
  • Not handling null result: findById returns null if no document matches, so always check before using the result.
  • Forgetting to await or use .then(): findById returns a promise, so you must await it or use .then() to get the result.
javascript
/* Wrong: Passing invalid id */
User.findById('invalid-id')
  .then(user => console.log(user))
  .catch(err => console.error('Error:', err.message));

/* Right: Validate id before querying or catch error */
const mongoose = require('mongoose');
const id = 'invalid-id';
if (mongoose.Types.ObjectId.isValid(id)) {
  User.findById(id)
    .then(user => {
      if (user) console.log(user);
      else console.log('User not found');
    })
    .catch(err => console.error(err));
} else {
  console.log('Invalid id format');
}
📊

Quick Reference

Remember these tips when using findById:

  • Use a valid ObjectId string as the id.
  • Always handle the case when the result is null.
  • findById returns a promise; use await or .then().
  • It is a shortcut for findOne({ _id: id }).

Key Takeaways

Use Model.findById(id) to find a document by its _id in Mongoose.
Always check if the result is null to handle not found cases.
Pass a valid ObjectId string to avoid casting errors.
Await the promise or use .then() to get the document.
findById is a convenient shortcut for findOne with _id.