I am interested in retrieving the documents from a mongoose collection in reverse order

I am trying to retrieve the most recent document from a collection using mongoose in conjunction with nodejs/expressjs.

In addition, I am implementing server-side pagination which prohibits me from reversing the order of retrieval after fetching.

exports.getProjects = (req, res, next) => {


const page = +req.query.page || 1; 
let totalItems;
Project
    .find()
    .countDocuments()
    .then(numProducts => {
        totalItems = numProducts;
        return Project.find()
            .skip((page - 1) * ITEMS_PER_PAGE)
            .limit(ITEMS_PER_PAGE)
    })
    .then(result => {
        return res.status(200).json({
            projects: result,
            currentPage: page,
            itemCount: totalItems,
            itemsPerPage: ITEMS_PER_PAGE,
        });
    })
    .catch(err => {
        console.log(err);
    })

};

Answer №1

To incorporate sorting into your query, make sure to specify the attribute that you want to sort by, such as date or a numerical value. You can utilize aggregation in the following manner:

const projectsCursor = await Project.aggregate([
{$match: Query},
{$sort: {field: 1}},
{$skip: number},
{$limit: someNumber}
]) 

Answer №2

Are you in search of the sort() function within mongoose? You can easily organize your collection using a variety of techniques.

Project.find({}).sort('test').exec(function(err, docs) { ... });
Project.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Project.find({}).sort({test: 1}).exec(function(err, docs) { ... });
Project.find({}, null, {sort: {date: 1}}, function(err, docs) { ... });

Choose one of these methods based on your specific needs and use the following code for smooth pagination.

app.get('/projects', async (req, res) => {
  // destructure page and limit and set default values
  const { page = 1, limit = 10 } = req.query;

  try {
    // execute query with specified page and limit
    const projects = await Project.find()
      .sort({ field : criteria})
      .limit(limit * 1)
      .skip((page - 1) * limit)
      .exec();

    // obtain total number of documents in the Project collection 
    const count = await Project.countDocuments();

    // send response with projects, total pages, and current page information
    res.json({
      projects,
      totalPages: Math.ceil(count / limit),
      currentPage: page
    });
  } catch (err) {
    console.error(err.message);
  }
});

Note: The criteria parameter can be any of the following: "asc", "desc", "ascending", "descending", 1, or -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

Tips for linking a Google Meet invitation to a Calendar Event (generated using a Service Account)

Having trouble creating a basic API call to set up a Google Calendar event with a Google Meet link embedded in it. Despite consulting the Calendar API Documentation and trying different examples, I am still facing difficulties. My setup involves a Servic ...

The POST method in Node JS request-promises does not properly handle string inputs

When I am trying to establish a connection between my node.js module and another server, I utilize the 'request-promise' library. My implementation for posting data looks like this: rp.({ method: 'POST', headers:{ 'Conte ...

The recently launched AWS Amplify application (serverless) is encountering a 403 Access Denied error

So I've gone ahead and created a brand new serverless (lambda) app using nodejs, expressjs, and ejs on AWS Amplify. After deploying it to the server using auto deployment, I tried accessing my app through the following URL: master.<...>.amplifya ...

What is the process of incorporating a lowercase normalizer into an Elasticsearch mapping object?

I'm attempting to incorporate a normalizer with a lowercase option into my mapping object, as detailed in the official Elasticsearch documentation Below is an example of my mapping object: const schema = { date: { type: 'date' ...

Error! The function worker.recognize(...).progress is throwing an error. Any ideas on how to resolve this

Here is the code snippet: //Imports const express = require('express'); const app = express(); const fs = require("fs"); const multer = require('multer'); const { createWorker } = require("tesseract.js"); co ...

Unable to establish headers once they have been issued - routing error

I have come across various solutions for this problem, but I am struggling to resolve it on my own. Therefore, I am sharing my code here in hopes of receiving assistance. I am new to this and would appreciate any help in understanding and fixing the issue ...

Struggling to launch the Node.js server on the OpenShift platform

Check out this snippet of code: var express = require('express'); var net = require('net'); var app = express(); var sock; //Establishing connection with mobile server on port 5132 console.log('Waiting for connection\nfrom ...

Installing and running Node.js within a tomcat server

After creating a web application using Angular, Node/Express, and MySQL, I faced an issue with deployment. My Angular app is running on a tomcat server connected to multiple PCs, but now I need to also deploy my backend (Node.js/Express.js) on the same s ...

Node.js: Capturing requests and responses for console logging

I'm currently working on a Hapi server using Good to log all requests and responses to the console. I've been able to successfully log responses but I'm facing issues with logging the body of the response, and for requests, I'm not gett ...

Express - Accessing 'Database' before initialization is not possible

const express = require('express'); const upload = require("express-fileupload"); const editJsonFile = require("edit-json-file"); const fs = require('fs'); const app = express(); app.use(upload()) app.use(express.url ...

Using Node.js to retrieve table data from a URL

My journey with Node JS and express is just beginning as I dive into building a website that serves static files. Through my research, I discovered the potential of using NodeJS with Express for this purpose. While I have successfully served some static HT ...

Tips for simulating next/router in vitest for unit testing?

Struggling with creating basic tests for our Next.js application that utilizes the useRouter() hook, encountering errors when using vitest. In search of solutions to mock next/router for unit testing in conjunction with vitest. ...

Issues are arising with the functionality of React-native link

After attempting to install and connect react-native sound in my project, I encountered an issue. When executing the following command within my project directory, react-native link react-native-sound the library fails to link and instead returns the fol ...

What is the best way to encode and split audio files so that there are no gaps or audio pops between segments when I put them back together?

In my current project, I'm developing a web application that involves streaming and synchronization of multiple audio files. To accomplish this, I am utilizing the Web Audio API in conjunction with HTML5 audio tags to ensure precise timing of the audi ...

Tips for reducing file size of an image post-upload using Sharp JS and Multer

I'm feeling a bit overwhelmed with my code right now, it seems like a real frankenstein's monster. I'm trying to figure out why this formula isn't producing the expected result. After uploading the file, I can retrieve the path using r ...

How does the use of nodejs, a server-side scripting language, tie into ReactJs or other front-end languages?

Can Node, being a server-side scripting language, be effectively utilized in the development of front-end applications such as npx create-react-app or npx create-nuxt-app? ...

Can Socket.io be connected only when a user logs in?

Exploring the fundamentals of Socket.io and aiming to establish a connection ONLY when a user logs in. The official documentation doesn't provide clear guidance on this specific implementation. Utilizing JWT for authentication and Node.js for server-s ...

Strip the URL prefixes to access files in the public directory easily

Despite creating a static public folder in app.js, When I visit "http://localhost:3000/calendars/add", the styles from the public folder are not applied. This is because Express has appended "calendars/add/" to the public folder URL. As a result, it appe ...

Is there a caching mechanism for packages in npm?

When I checked my server, it seems that npm is not caching any packages as the cache directory appears to be empty. #www@iZ2zefuufnen6rfx7c81u7Z:~/.npm$ nvm current v9.4.0 # www@iZ2zefuufnen6rfx7c81u7Z:~/.npm$ npm config get cache /home/www/.npm # www@iZ2z ...

Save the result of a terminal command into an sqlite database

When I run a particular shell command in node js, the output is displayed on the console. Is there a method to store this output in a variable so that it can be POSTed to an Sqlite database? const shell = require('shelljs'); shell.exec('a ...