Open In App
Related Articles

Mongoose | findOne() Function

Improve Article
Improve
Save Article
Save
Like Article
Like

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: Database

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.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 17 Mar, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials