Sling Academy
Home/Node.js/Mongoose Model.findById() function explained (with examples)

Mongoose Model.findById() function explained (with examples)

Last updated: December 30, 2023

The Model.findById() method in Mongoose is a staple for MongoDB document queries within a Node.js application. Mongoose, an Object Data Modeling (ODM) library for MongoDB and Node.js, simplifies interactions with MongoDB. The findById() function specifically has been available since early versions of Mongoose and is designed to fetch a document by its unique _id.

The primary purpose of the Model.findById() method is to retrieve a single document from a MongoDB collection by its _id, which is a unique identifier automatically generated by MongoDB for each document.

Syntax and Parameters

Model.findById(id, [projection], [options], [callback])
  • id – The unique _id value of the document to find.
  • projection (optional) – A string or object specifying which fields to include or exclude from the result document.
  • options (optional) – Query options config object.
  • callback (optional) – A callback function that receives the query result.

If no callback is provided, the method returns a Query, which can be thenable. Thus, it can be used with promises and async/await.

The findById() method returns a Promise that resolves to the document if found, or null if not.

Examples

Basic findById Example

The following example demonstrates the use of findById() in a very simple scenario, where no additional options or projection are specified.

import mongoose from 'mongoose';
const { Schema } = mongoose;

mongoose.connect('mongodb://localhost:27017/yourDB');

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

async function getUserById(userId) {
  try {
    const user = await User.findById(userId);
    console.log(user);
  } catch (error) {
    console.error('An error occurred:', error);
  }
}

getUserById('someUserId');  // Replace 'someUserId' with an actual _id from your database

Finding a Document With Projection

In this example, we use the projection parameter to return only the name and email fields, excluding the _id.

async function getUserByIdWithProjection(userId) {
  const user = await User.findById(userId, 'name email -_id').exec();
  console.log(user);
}

getUserByIdWithProjection('someUserId');  // Replace 'someUserId' with an actual ID

Conclusion

The Model.findById() method in Mongoose is a concise and powerful way to search for documents by their unique identifier. Its flexibility to use callbacks, promises, or async/await makes it a vital part of any Mongoose-based application’s querying arsenal. As you progress in working with Mongoose, mastering findById() is essential.

Next Article: Mongoose: Sorting Documents by Multiple Fields

Previous Article: Using the Mongoose Model.find() function (with examples)

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates