The Wayback Machine - https://web.archive.org/web/20240926213805/https://www.geeksforgeeks.org/mongoose-findone-function/
Open In App

Mongoose findOne() Function

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

findOne in Mongoose

findOne() is used when you want to retrieve a single document from a collection based on a specific condition, such as finding a user by their email or username.

Syntax:

Model.findOne(query, [projection], [options], [callback])

Parameters:

  • Model: This is the name of the collection used to retrieve the document corresponding to the provided ID.
  • query: An object specifying the conditions that the returned document(s) must match.
  • projection (optional): Specifies which fields to include or exclude from the returned document.
  • options (optional): Additional options, such as sorting or limiting the results.
  • callback: findOne also accepts a callback function, which can manage errors or perform actions with the retrieved document.

Features

  • Efficiently fetches a single document that matches the criteria.
  • Supports complex queries with multiple conditions.
  • Allows you to specify which fields to include or exclude in the returned document.
  • Works seamlessly with promises and async/await for cleaner code.

Steps to Install Mongoose Module:

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:

NodeProj

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

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

Example: This example connects to a MongoDB database using Mongoose and uses the findOne() function to retrieve a single user document where the age is greater than or equal to 5.

JavaScript
// Filename - index.js

const mongoose = require('mongoose');

// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
    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: Run the following command in the terminal

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

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.

Summary

The findOne() function in Mongoose is a powerful and efficient method for retrieving a single document from a MongoDB collection. It allows for flexible querying, field projection, and integrates well with promises, making it an essential tool for working with MongoDB in Node.js applications.


Previous Article
Next Article

Similar Reads

Mongoose Query.prototype.findOne() API
The Mongoose Query API findOne() method is used to find a single document, from a collection, using the MongoDB query system. Syntax: Query.prototype.findOne(filter, projection, options) Parameters: It accepts the following 4 parameters as mentioned above and described below: filter: It is a mongoose object which identifies the existing document to
3 min read
Error: Warning: Accessing non-existent property 'findOne' of module exports inside circular dependency
It looks like you're trying to use a method called findOne but it doesn't exist. This error message suggests that there is a circular dependency in your code, which means that two or more modules are trying to import each other. This can cause problems because the modules can't be resolved properly. This error indicates that there is a problem with
3 min read
How to Perform a findOne Operation in MongoDB using Node.js?
The findOne operation in MongoDB is used to get a single document from the collection if the given query matches the collection record. While using findOne, if more than one record is there with the exact same match, then it will return the very first one. We will use this operation if we need to fetch a specific record, like a user's profile, any
4 min read
MongoDB - FindOne() Method
MongoDB is a widely used NoSQL database that allows for flexible and scalable data storage. One of its essential methods, findOne() which is used to retrieve a single document from a collection that matches the specified query criteria. This method is particularly useful when we need to fetch one specific document rather than multiple documents. In
4 min read
Mongoose mongoose.model() Function
The mongoose.model() function of the mongoose module is used to create a collection of a particular database of MongoDB. The name of the collection created by the model function is always in plural format mean GFG to gfss and the created collection imposed a definite structure. Syntax: mongoose.model(<Collectionname>, <CollectionSchema>
2 min read
Mongoose | updateMany() Function
The updateMany() function is same as update(), except MongoDB will update all documents that match the filter. It is used when the user wants to update all documents according to the condition. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose
2 min read
Mongoose | findOneAndDelete() Function
The findOneAndDelete() function is used to find a matching document, remove it, and passes the found document (if any) to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your mong
2 min read
Mongoose | findByIdAndDelete() Function
The findByIdAndDelete() function is used to find a matching document, removes it, and passing the found document (if any) to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your m
2 min read
Mongoose | findOneAndRemove() Function
The findOneAndRemove() function is used to find the element according to the condition and then remove the first matched element. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your mongoose v
2 min read
Mongoose | findOneAndReplace() Function
The findOneAndReplace() function is used to find a matching element, replaces it with the provided element, and passes the returned doc to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you ca
2 min read
Mongoose | countDocuments() Function
The countDocuments() function is used to count the number of documents that match the filter in a database collection. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose After installing mongoose module, you can check your mongoose version in th
2 min read
Mongoose | exists() Function
The exists() function returns true if at least one document exists in the database that matches the given filter, and false otherwise. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your mongo
2 min read
Mongoose | where() Function
The where() function is used to create a Query, applies the passed conditions and returns the Query. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt usin
2 min read
Mongoose | replaceOne() Function
The replaceOne() function is same as update() function except MongoDB replace the existing document with the given document (no atomic operators like $set). Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, yo
2 min read
Mongoose | remove() Function
The remove() function is used to remove the documents from the database according to the condition. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt using
2 min read
Mongoose | update() Function
The update() function is used to update one document in the database without returning it. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt using the comm
2 min read
Mongoose | estimatedDocumentCount() Function
The estimatedDocumentCount() function is quick as it estimates the number of documents in the MongoDB collection. It is used for large collections because this function uses collection metadata rather than scanning the entire collection. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package
2 min read
Mongoose count() Function
The Query.prototype.count() function is used to count the number of documents in a collection. This functions basically specifies this query as a count query. Syntax: Query.prototype.count() Parameters: This function accepts one array parameter i.e. callback function. Return Value: This function returns Query Object. Installation of mongoose module
2 min read
Mongoose Query() Function
The Query constructor is used for building the queries. So the user does not need to instantiate a Query directly. The `query` is an instance of `Query`. Syntax: Query() Parameters: This function has optional parameters like model, condition, collection and options. Return Value: This function returns Query object. Installation of mongoose module:
2 min read
Mongoose Queries Model.replaceOne() Function
The Queries Model.replaceOne() function of the Mongoose API is used to replace an existing document with the given document. It replaces only the first document that is returned in the filter. Syntax: Model.replaceOne( filter, doc, options, callback ) Parameters: It accepts the following 4 parameters as mentioned above and described below: filter:
3 min read
Mongoose Queries Model.findOneAndUpdate() Function
The Queries Model.findOneAndUpdate() function of the Mongoose API is used to find and update an existing document with the information mentioned in the "update" object. It finds and updates only the first document that is returned in the filter. Syntax: Model.findOneAndUpdate(conditions, update, options, callback) Parameters: It accepts the followi
3 min read
Mongoose Queries Model.updateOne() Function
The Queries Model.updateOne() function of the Mongoose API is used to update an existing document with the information mentioned in the "update" object. It updates only the first document that is returned in the filter. Syntax: Model.updateOne(filter, update, options, callback ) Parameters: It accepts the following 4 parameters as mentioned above a
3 min read
Mongoose Schema Connection.prototype.model() Function
The Mongoose Schema API Connection.prototype.model() of the Mongoose API is used on the Connection objects. It allows us to define new model in the MongoDB database for particular connection object. It is used to define and retrieve models in and from the database. Let us understand models() method using an example. Syntax: connectionObject.model(
3 min read
Mongoose Document API .prototype.isDirectSelected() Function
The Mongoose Document API.prototype.isDirectSelected() method of the Mongoose API is used on the Document model. It allows us to check whether particular path or field from the collection is explicitly selected or not. Let us understand isDirectedSelected() method using an example. Syntax: document.isDirectSelected( path ); Parameters: This method
3 min read
Mongoose Document API .prototype.$set() Function
The Mongoose Document API.prototype.$set() method of the Mongoose API is used on the Document model. It allows to set the values for the particular field in the collection. This method we can use on any model object to assign or set the value for fields. Let us understand the set() method using an example. Syntax: document.$set( path, value, type,
3 min read
Mongoose Schema API Connection.prototype.deleteModel() Function
The Connection.prototype.deleteModel() method of the Mongoose API is used on the Connection object. It allows us to remove the model from the connection. Using this method we can clean the model associated with the connection. Let us understand deleteModel() method using an example. Syntax: connection.deleteModel( name ); Parameters: This method ac
3 min read
Mongoose Connection.prototype.createCollection() Function
The Mongoose Schema API Connection.prototype.createCollection() method of the Mongoose API is used on the Connection object. It allows us to create collection explicitly by providing the name of the collection and options to related to it. Let us understand the createCollection() method using an example. Syntax: connection.createCollection( collect
2 min read
Mongoose Connection.prototype.get() Function
The Mongoose Schema API Connection.prototype.get() method of the Mongoose API is used on the Connection object. It allows us to get the value of the option properties. Using this method we can fetch the values of different properties from options object. Let us understand get() method using an example. Syntax: connectionObject.get( key ); Parameter
2 min read
Mongoose SchemaTypes schema.path() Function
The Mongoose SchemaTypes schema.path() function is used to get the instantiated schema type for a given path. This function can be used to inspect the schema type and validator for a given path. Syntax: schema.path( propertyName ); Parameters: It accepts a single parameter as mentioned above and described below: propertyName: It is the name of the
3 min read
Mongoose Queries Model.findByIdAndUpdate() Function
The Mongoose Queries findByIdAndUpdate() function is used to search for a matching document, update it in accordance with the update argument while giving any options, then return the found document (if any) to the callback. Installation of Mongoose Module: Step 1. You can visit the link to Install the mongoose module. You can install this package
7 min read