Trusted answers to developer questions

What is find() in Mongoose?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Mongoose’s find() method is a query to retrieve a document or documents that match a particular filter.

Syntax

// Using a callback or callafter function
Model.find([filter], callback)
// Using async and await
const ourQuery = await Model.find([filter]);

Return value

The returned value could be an array of documents, a single document if it matches only one, or an empty array if no document is matched.

Example

The following code demonstrates the use of the find() method in Mongoose.

Using find() with a simple filter

When a document is queried using a certain field, it either returns 1, more than one, or an empty array of documents if there is no match. See the example below:

app.get("/findname", async (req, res)=>{
try{
if(req.query.name){
let singlePerson = await Person.find({name: req.query.name}).exec();
return res.json(singlePerson);
}else{
res.json({error: "No name query found inside request"})
}
}catch(error){
throw error
}
})

In the code above, we created a query that will match the Person collection. The query is to match any document with the name field as the req.query.name value. If you don’t understand how to use the req.query, take a look at my shot What is req.query in expressJs.

When the name query is retrieved, a document with the name field as the query value is retrieved.

Using find() with an advanced filter

Now let’s take a look at a different kind of filter. This time we want to search for a range of commits using the commit field. We can do this by using the operators $gte and $lte.

app.get('/commits', async (req, res)=>{
try{
if(req.query.from && req.query.to){
let from = req.query.from;
let to = req.query.to;
let singlePerson = await Person.find({commit: {$gte:from , $lte:to}}).exec();
res.json(singlePerson)
}else{
res.json({error: "No from and to query parameters found"})
}
}catch(error){
throw error
}
})

Looking at the code above, we used the query of from and to sort for commits at a particular range based on these values. The response will be an array of documents if it is matched or an empty array if no document is found.

Example

Take a look at the full code below. We create an express server, together with our Person model and the Schema.

require('dotenv').config();
const express = require('express');
const app = express();
const mongoose = require("mongoose");
mongoose.connect(process.env.DB_ONLINE, {
useNewUrlParser: true,
});
const db = mongoose.connection;
db.on("error", () => {
console.error.bind(console, 'MongoDB connection error:')
})
db.on("open", () => {
console.log("database running successfully");
})
const Person = mongoose.model("Person", new mongoose.Schema({
name: String,
title: String,
commit: Number
})
)
const createManyDocuments = async () =>{
try {
await Person.deleteMany({});
let persons = await Person.create(
[
{
name: "Theodore",
title: "MERN Stack Developer",
commit: 1000
},
{
name: "Chidera",
title: "Network Administrator",
commit: 1000
},
{
name: "Elijah",
title: "Backend Developer",
commit: 200
},
{
name: "Emeka",
title: "Web Developer",
commit: 500
}
]
)
return persons
}
catch (error) {
throw error
}
}
app.get("/", async (req, res) => {
let persons = await createManyDocuments();
res.json({documents: persons});
});
app.get("/findname", async (req, res)=>{
try{
if(req.query.name){
let singlePerson = await Person.find({name: req.query.name});
return res.json(singlePerson);
}else{
res.json({error: "No name query found inside request"})
}
}catch(error){
throw error
}
})
app.get('/commits', async (req, res)=>{
try{
if(req.query.from && req.query.to){
let from = req.query.from;
let to = req.query.to;
let singlePerson = await Person.find({commit: {$gte:from , $lte:to}}).exec();
res.json(singlePerson)
}else{
res.json({error: "No from and to query parameters found"})
}
}catch(error){
throw error
}
})
const port = process.env.PORT || 3000;
app.listen(port, function() {
console.log(`Listening on port ${port}`);
});

The createManyDocuments() function first clears the collection of any documents and creates new documents, which are documents in the array passed into the Person.create() method. At any get request to the "\" route, the function is called.

When the "\findname" route is requested and populated with a name query value, then the document with the name value is returned. And then there is the get request to "\commits" which sorts the documents within the range specified in the values of the request queries from and to.

RELATED TAGS

mongoose
find
mongodb

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
Did you find this helpful?