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 byid, it is better to use thefindById()method.
Model.findById(id)
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.
findById returns the document where the _id field matches the specified id. If the document is not found, the function returns null.
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 mongooseconst mongoose = require("mongoose");// creating a Schema with mongooselet Language = mongoose.model("Language", new mongoose.Schema({name: String,country: [String],}))// create a typical MongoDB idlet id = "6120216fbb75d313c4d65af4"// make a query with the `findById()` functionconst language = await Language.findById(id)console.log(language)/*OUTPUT:a single document is returned or null if not found*/
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.