This content originally appeared on CodeSource.io and was authored 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 }).
The post How to use findById in Mongoose appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Deven
Deven | Sciencx (2021-10-15T11:38:45+00:00) How to use findById in Mongoose. Retrieved from https://www.scien.cx/2021/10/15/how-to-use-findbyid-in-mongoose/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.