node

How to use findById in Mongoose


Each document inside MongoDB has a unique id associated with it, which helps to identify the document independently. It is similar to primary key defined in MySQL.

findById:

This method takes Id as input parameter & returns the single matching document. FindById is shortcut of findOne({ _id: id })

example:

const id = 'xyz45a99bde77b2efb20e';
const document = await User.findById(id);
document.name; // 'John Doe'
document.age; // 29

Once a user hits this query, internally MongoDB calls the findOne().

Difference between findById() & findOne():

The main difference between these two methods is how MongoDB handles the undefined value of id. If you use findOne({ _id: undefined }) it will return arbitrary documents. However, mongoose translates findById(undefined) into findOne({ _id: null }).


Share on social media

//