What is the limit() method in Mongoose?

The limit() method in Mongoose is used to specify the number or a maximum number of documents to return from a query.

Syntax

query.limit(number)

Here, query is the query that will match and return documents that match.

Parameter

The parameter this method takes is a number.

  • number: this is the maximum number of documents to return by the query.

Code

Let’s create an Express.js server that has a Person schema. We will create two routes. One is the root route "\", and the other is the route "\limit".

The former will create documents and store them in our database, as well as serve a JSON response of the elements created.

The latter route will get all the documents but will limit them to two.

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
})
)
// A function to delete stored documents and create new ones.
const createManyDocuments = async () =>{
try {
await Person.deleteMany({});
let persons = await Person.create(
[
{
name: "Theodore Kelechukwu Onyejiaku",
title: "MERN Stack Developer",
commit: 1000
},
{
name: "Chidera Ndukwe",
title: "Network Administrator",
commit: 1000
},
{
name: "Elijah Azubuike",
title: "Backend Developer",
commit: 200
},
{
name: "Emeka Isiolu",
title: "Web Developer",
commit: 500
}
]
)
return persons
}
catch (error) {
throw error
}
}
// FIRST ROUTE: creates a collection and populates with documents
app.get("/", async (req, res) => {
let persons = await createManyDocuments();
// Returns a json of the 4 documents created!
res.json({documents: persons});
});
app.get("/limit", async (req, res)=>{
try{
// Limit result to just 2
let persons = await Person.find({}).limit(2).exec();
res.json(persons)
}catch(error){
throw error
}
})

Expected output

When we access the "\limit" route the returned result is an array of two documents, as shown below.

As we can see, only two documents are returned.