Mongoose findOne() Function

The findOne() function is used to find one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition. 

Syntax:

Model.findOne(id)

Parameters:

  • Model: This is the name of the collection used to retrieve the document corresponding to the provided ID.
  • id: This is the identifier for the document you intend to locate.
  • callback`findOne` also accepts a callback function, which can manage errors or perform actions with the retrieved document.

Steps to Installation of Mongoose ModuleMongoose:

Step 1: You can visit the link Install Mongoose module. You can install this package by using this command.

npm install mongoose

Step 2: After installing the mongoose module, you can check your mongoose version in the command prompt using the command.

npm version mongoose

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"mongoose": "^7.6.5",
}

Example: Below the code example for the findOne() method:

javascript




const mongoose = require('mongoose');
 
// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/w3wiki', {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
 
// User model
const User = mongoose.model('User', {
    name: { type: String },
    age: { type: Number }
});
 
// Find only one document matching
// the condition(age >= 5)
 
// Model.findOne no longer accepts a callback
 
User.findOne({age: {$gte:5} })
   .then((docs)=>{
       console.log("Result :",docs);
   })
   .catch((err)=>{
       console.log(err);
});


Steps to run the program:

node index.js

Below is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database like we have used the Robo3T GUI tool as shown below:

Console Output:

So this is how you can use the mongoose findOne() function that finds one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition.


Contact Us