What is skip() in Mongoose?

In Mongoose, the skip() method is used to specify the number of documents to skip. When a query is made and the query result is returned, the skip() method will skip the first n documents specified and return the remaining.

Syntax

query.skip()
// OR
Query.prototype.skip(<offset>)

Parameter

  • offset: The number of documents to skip from the query result.

Return value

It returns an array of documents according to the query, excluding the initial skipped documents as specified.

Code

In the example below, we will create a Schema, query the Schema, and call the skip() method on it.

Note that we used estimatedDocumentCount() to reveal how many documents are already in the collection.

// import mongoose
const mongoose = require("mongoose");
// creating a Schema with mongoose
let Person = mongoose.model("Person", new mongoose.Schema({
name: String,
age: Number
})
)
// Get number of documents already in collection
Person.estimatedDocumentCount() // returns 100
// create a query and call the `skip()` method
let persons = await Person.find().skip(20)
console.log(persons) // 80 documents are returned

From the example above, 100 documents are already in the collection. With the skip(20) function, the first 20 documents are not returned, while the remaining 80 are.

Free Resources