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.
Installation of mongoose module:
You can visit the link to Install the mongoose module. You can install this package by using this command.
npm install mongoose
After installing the mongoose module, you can check your mongoose version in the command prompt using the command.
npm version mongoose
After that, you can just create a folder and add a file, for example, index.js. To run this file you need to run the following command.
node index.js
Project Structure:
Filename: index.js
javascript
const mongoose = require( 'mongoose' ); // Database connection 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:
Make sure you have installed the mongoose module using the following command:
npm install mongoose
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:
Run the index.js file using the below command:
node index.js
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.
Please Login to comment...