How to use findById in Mongoose
Posted on: October 15, 2021 by Deven
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
//