Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

mongoose
mongodb
communitycreator

What is findById() in Mongoose?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In MongoDB, all documents are unique because of the _id field or path that MongoDB uses to automatically create a new document.

For this reason, finding a document is easy with Mongoose. To find a document using its _id field, we use the findById() function.

In some cases, you might be tempted to use the findOne() method. However, when you only want to query documents by id, it is better to use the findById() method.

Syntax

Model.findById(id)

Parameters

  • Model: This is the collection name to find the document that matches the specified id.

  • id: This is the id of the document you wish to find.

  • callback: findById can also take a callback function that can handle an error or do something with the document after it has been returned.

Return value

findById returns the document where the _id field matches the specified id. If the document is not found, the function returns null.

Code

In the example below, we will create a Schema for our database. We will also use a typical MongoDB id. Then, we will make a query to find a document.

// import mongoose
const mongoose = require("mongoose");
// creating a Schema with mongoose
let Language = mongoose.model("Language", new mongoose.Schema({
name: String,
country: [String],
})
)
// create a typical MongoDB id
let id = "6120216fbb75d313c4d65af4"
// make a query with the `findById()` function
const language = await Language.findById(id)
console.log(language)
/*
OUTPUT:
a single document is returned or null if not found
*/
The findById() function

In the code above, a Language schema is created for a Language collection in our database. We use findById() to find a document whose _id field we create as 6120216fbb75d313c4d65af4. If the document found is found, then the document is returned. Otherwise, null is returned.

RELATED TAGS

mongoose
mongodb
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring