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…

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

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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » How to use findById in Mongoose." Deven | Sciencx - Friday October 15, 2021, https://www.scien.cx/2021/10/15/how-to-use-findbyid-in-mongoose/
HARVARD
Deven | Sciencx Friday October 15, 2021 » How to use findById in Mongoose., viewed ,<https://www.scien.cx/2021/10/15/how-to-use-findbyid-in-mongoose/>
VANCOUVER
Deven | Sciencx - » How to use findById in Mongoose. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/10/15/how-to-use-findbyid-in-mongoose/
CHICAGO
" » How to use findById in Mongoose." Deven | Sciencx - Accessed . https://www.scien.cx/2021/10/15/how-to-use-findbyid-in-mongoose/
IEEE
" » How to use findById in Mongoose." Deven | Sciencx [Online]. Available: https://www.scien.cx/2021/10/15/how-to-use-findbyid-in-mongoose/. [Accessed: ]
rf:citation
» How to use findById in Mongoose | Deven | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.