Succession of Mongoose queries

One interesting feature of my model is the ability to chain queries like find(), limit(), and skip(). However, there arises a question: How can I apply the limit or skip function to the output of Model.find() if the returning value does not inherently contain these functions?

For instance, consider the following code:

const mongoose = require("mongoose");
const password = encodeURIComponent("*****");
const username = encodeURIComponent("*****");

async function main() {

    await mongoose.connect(`mongodb+srv://${username}:${password}@cluster0.e5rojbd.mongodb.net/test?ssl=true&retryWrites=true&w=majority`);
    const userSchema = new mongoose.Schema({
        name: String
    });
    const Name = mongoose.model('names', userSchema);
    const limitedNames = Name.find().limit(2).skip(1);
    console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(limitedNames)))
    // output is [ 'constructor', '_queryMiddleware' ]
}
main().catch(err => console.log(err));


This code successfully applies limit and skip functions, but how is it achieved?

Answer №1

.limit and .skip functions do not create a chain within the find query; instead, they adjust the command before it is transmitted to the server.

Model.find() generates a query object that acts as a type of promise. When this object is combined with await or .exec, a find database command is dispatched to the mongod server.

The limit, skip, and sort functions fill in their respective fields within the query object, which are then included in the command when await or exec are utilized.

Give it a shot

const restrictedNames = await Name.find().limit(2).skip(1)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the fastest and most efficient method to confirm that all rows in a 2D array are of equal length?

Imagine you have a 2D array like this: const matrixRegular = [ ['a', 'b', 'c'], ['e', 'f', 'g'], ]; Now, let's think about how we can check if every row in this matrix has the same ...

Acquire JSON data from a URL and display it on the webpage

I'm facing an issue where the JSON data I'm trying to fetch from a URL is not displaying due to an uncaught reference error in my code. How can I modify the code to ensure that the data gets shown? var url = "https://fantasy.premierleague.com/ ...

Tips for receiving a reply from S3 getObject in Node.js?

Currently, in my Node.js project, I am working on retrieving data from S3. Successfully using getSignedURL, here is the code snippet: aws.getSignedUrl('getObject', params, function(err, url){ console.log(url); }); The parameters used are: ...

How can we utilize Javascript to add both days and years to the current date?

Is there a way to get the current date, add 1 day to it and then also add 1 year? If so, how can this be done? ...

A step-by-step guide for setting up MongoDB on a "Blank Node.js Console Application" project in VS2015 with TypeScript

Here is my process: First, I installed MongoDB Next, I opened Visual Studio 2015 Then, I created a new project by going to "File" -> "New" -> "Project" -> "TypeScript" -> "Blank Node.js Console Application" After that, I opened the project fo ...

What is the reason that PHP has the ability to set Cookies but Local Storage does not?

Let's take a step back to the era of cookies, not too far back since they are considered old but still quite relevant. PHP allows you to set and read them even though they are a client-side technology; however, JavaScript can also be used completely o ...

Best practices for efficiently creating documents in Mongoose when dealing with fields containing an unpredictable number of items

After researching and experimenting with demo code and tests, I have been working on implementing a school management system. Now, I am seeking advice from experienced mongoose developers on the best practice for creating a schema that allows for flexibili ...

Implementing promise-based looping for multiple GET requests in node.js

As a newcomer to promises, I've been searching for the right answer or pattern without much luck. Currently using node.js v4.2.4 and exploring The task seems simple enough... I need to execute multiple asynchronous blocks in a specific order, with on ...

Struggling to get a basic HTML form to function with JavaScript commands

In my form, there are two input fields and a button. Upon clicking the button, a JavaScript function is triggered which multiplies the values entered in the inputs. The result is then displayed in a <p> element and evaluated through an if else statem ...

What purpose does the .set() function serve in Node.js with Express?

As I delve into learning Node syntax, there's this particular code snippet that has caught my curiosity. Can you shed some light on its purpose? server.set('views', __dirname); ...

Sending numerous messages from a single event using Socket.io

After an exhaustive search, I have yet to find a solution to my problem. I am attempting to send a message from the server every time it detects a file change in a specific directory. However, instead of sending just one message, it sends the same message ...

Azure-Graph is reporting an error: 'Invalid or missing Access Token.'

In my Node.js project, I effortlessly integrate azure APIs. Logging in: const MsRest = require('ms-rest-azure'); MsRest.loginWithServicePrincipalSecret(keys.appId, keys.pass, keys.tenantId); Creating a resource group: const { ResourceManageme ...

Tips for minimizing the padding/space between dynamically generated div elements using html and css

Currently, I have 4 dropdown menus where I can choose various options related to health procedures: Area, specialty, group, and subgroup. Whenever I select a subgroup, it dynamically displays the procedures on the page. However, the issue I am facing is th ...

Using JavaScript to extract data from a JSON-formatted URL

I am currently facing a challenge with parsing JSON data from a specific URL. Despite my efforts, I am unable to retrieve any information related to the "ask" and "bid" values from this JSON feed. The URL in question is . The structure of the JSON data is ...

I want to know how to shift a product div both horizontally and vertically as well as save its position in And Store

How can I animate and move a product div horizontally & vertically, and save its position for future visits? I need to move the div with animation in a specific sequence and store the position using PHP. Buttons <button type="button" href ...

Determining the successful completion of an ajax request using jQuery editable plugin

I recently started using Jeditable to enable inline editing on my website. $(".video_content_right .project_description").editable(BASE_URL+"/update/description", { indicator: "<img src='" + BASE_URL + "/resources/assets/front/images/indicator ...

"Why is it that the keypress event doesn't function properly when using the on() method

My goal is to capture the enter event for an input field $("input[name='search']").on("keypress", function(e){ if (e.which == '13') { alert('code'); } }); This is the HTML code snippet: <input name="searc ...

Tips for showcasing JavaScript variables on a webpage

I am working with various JavaScript variables that involve displaying values inside div elements. goalDiv = "<div class=goal-parent id=goal-parent"+Id+">"+ "<div class=goal>"+ "<div class=top-layer>"+ "<div class=compone ...

assign a JSON key to a variable

Is there a way to use a variable as a JSON key in JavaScript? var chtid = "1234" firebase.database().ref().set ({chtid :"hi"}); In this case, chtid is the variable. I have attempted this method without success: var chtid = "1234" firebase.database().re ...

Deactivate the AJAX button after the specified number of clicks

Imagine I have a model called Post, and it can be associated with up to n Comments (where the number is determined by the backend). Now, let's say I have a view that allows users to add a Comment through an AJAX request. What would be the most effecti ...