I'm looking to sort a specific field that contains an array when making a GET request from an express.js endpoint using mongoose. How can I accomplish this?

I have defined a User schema as follows:

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
    name: {
        type: String
    },
    subscriptions: [{
        userID: {
            type: String,
            required: true,
        },
        subscriptionDate: {
            type: Date,
            required: true,
            default: Date.now
        }
    }]
})

In addition, I have a routes.js file with the following content:

const express = require('express')
const router = express.Router()
const User = require('User')

router.get('/', async (req, res) => {
    try {   
        const users = await User.find()
        res.json(users)
    } catch (err) {
        res.status(500).json({message: err.message})
    }
})

When making a GET request, I am facing an issue where I need the 'subscriptions' field to be sorted by 'subscriptionDate', displaying only the 5 most recent subscriptions while showing all other information normally. As a beginner in express, mongoDB, and mongoose, I hope my explanation is clear.

How can I achieve the desired output?

For reference, here is my server.js file:

require('dotenv').config();

const express = require('express');
const app = express();
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/subscribers');
const db = mongoose.connection;
db.on('error', (error) => console.error(error));
db.once('open', () => console.log('Connected to Database'));

app.use(express.json());

const router = require("./routes");
app.use('/routes', router);

app.listen(3000, () => console.log('Server Started.'))

I have attempted using collections.find().sort(), which sorted all users based on subscriptions. I also tried using aggregate([$unwind]), resulting in splitting users into multiple documents based on their subscriptions.

Answer №1

If you're looking to fetch all users while organizing subscriptions and maintaining only the top five, you can achieve this by utilizing MongoDB version 5.2 or newer:

db.users.aggregate([
{
  $set: {
    subscriptions: {
      $slice: [
        {
          $ifNull: [
            {
              $sortArray: {
                input: "$subscriptions",
                sortBy: {
                  subscriptionDate: -1
                }
              }
            },
            []
          ]
        },
        5
      ]
    }  
  }
}
])

Check out the complete example at: https://mongoplayground.net/p/9JkLmNqAe7R

I've utilized the $slice operator to retain the top 5 elements in the subscription array that I sorted using the $sortArray operator (which is supported in versions 5.2 and higher)

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

Oops! The Vue star rating encountered an error because it couldn't read the length property of an undefined value at line 26 of listToStyles.js

Encountering an issue with the getRating function in Vue while using the Vue-star-rating package in Laravel. Unsure of what the problem may be. getRating(){ var pathArray = location.pathname.split('/'); v ...

What is the solution for the error message "TypeError: app.use() is seeking a middleware function"?

I am a beginner in Node.js and have encountered an issue in my passport.js or signupLogin.js file with the error message, app.use() requires a middleware function that I am struggling to resolve. I suspect it may be related to the signupLogin route, as th ...

Should npm run start be used instead of npm start in Create React App?

The starting point for our application in Create React App is npm start. However, when we want to build the app, we use npm run build instead of npm run start. It may be confusing why npm start works this way. Is it a default npm script command? ...

Executing various count() queries on a MongoDB using mongoose

Hey there, I consider myself a MongoNoob and I know this question has probably been asked before in various ways, but I haven't found a specific solution yet. Let's imagine I have two Moongoose Models set up like this: var pollSchema = mongoose. ...

Incorporating random image selection into a React application

Im facing an issue with my app that randomly selects pokemon from a list to build a team for the user. While I know how to import images for use in a react app, I'm unsure how to serve an image to a user using react. Currently, the sprites are locate ...

Reaching out to a particular individual with a message

In my coding dilemma, I am trying to make a bot send a message every minute to a particular user, not all users. The struggle is real! guild.members.cache.forEach(member => { setInterval(() => { member.send('hello').catch(error =&g ...

Encase the text within a div element while leaving out any child elements

I have encountered a puzzling issue that has been troubling me for the past two days, and I have yet to find a solution. The Dilemma: Here is the HTML code in question: <div class="string-box"> Text 1 wrap me <span clas ...

Passing a global variable as an argument to a jQuery function is not allowed

I am attempting to display local weather information using an API. The API URL is generated based on the user's current position. var lat, lon = null; var key = "mykey"; var api = ""; function setApi(position){ lat = Math.round(position.coords.lati ...

Learn the magic of jQuery: toggling table row visibility effortlessly!

I am currently working on a PHP application using Zend Framework that includes a table with a large number of rows. Most users interact with either the first or second row about 99.9% of the time. Only around 0.1% of users need to revisit previous rows f ...

Mastering the art of utilizing sequelize and promises effectively

I'm currently learning how to create apps using expressJS and Sequelize. I could really use some help as I'm more accustomed to sequential programming. My project involves two models: Todo (id, title) and TodoItem (id, content, complete, todoId). ...

The npm copy script is not functioning properly on the Windows 8.1 operating system

I am working on a sapui5 project and I need to execute the following npm script from my package.json: "scripts": { "flatten": "copy -r \\dist\\resources\\test\\commonjslib\\* dis ...

A cautionary alert is triggered by vsCode when analyzing seemingly correct code sourced from vue.js documentation

While using Visual Studio Code version 1.13.1V and referring to the vue.js guide on lazy loading, I encountered an issue when writing the following code snippet: import Vue from 'vue' import Router from 'vue-router' const Health = () = ...

What is the best method for importing Bootstrap into SvelteKit?

I am currently working on a SvelteKit website. I have integrated Bootstrap 5 into my project by adding it to the app.html file provided by the SvelteKit Skeleton starter project: <!-- Bootstrap styles and javascript --> <link rel="stylesheet ...

How do I send JSON data to an MVC Controller?

I'm working with a JSON object that has nested arrays and need to send it to a controller for processing. Here's how I'm making my jQuery.ajax call: $.ajax({ url: "@Url.Action("ExportJson")", type: "POST", ...

Dynamic adjustment of div size to fit the screen when resizing, based on the svg proportions

Is it possible to use CSS and HTML to automatically adjust the colored divs around the black SVG to fill in any extra width or height of the pink space when the screen size is resized? There is a pink div behind the logo that serves as an example of the sp ...

Converting all numbers separated by commas to numbers separated by periods in a string using JavaScript

Imagine a scenario where you have a string containing numbers, such as, test() test 12,01% test (12,4) 12.3 s 2 some other text, other text, 2,text Your task is to replace the numbers with decimals instead of commas without altering anything else in the ...

Creating custom services that modify or extend default services in a shared module

I am facing a dilemma with my shared module in AngularJS 1.6.5. This module is designed to be used across multiple applications, each requiring different services within the module to be overridden to cater to their specific needs. These variations are mai ...

Uploading Massive Form Data Using Angular JS

After spending countless hours on this project, I still can't figure out how to post data into a table using JavaScript objects. While I can easily work with smaller data sets, I'm struggling with handling multiple nested objects. EDIT: ...

Firestore/Javascript error: FirebaseError - The data provided is invalid for the DocumentReference.set() function. An unsupported field value of 'undefined'

I keep encountering this error Error creating user: FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field diabetesComplication) After some investigation, I realized that the iss ...

The 'views' folder cannot be found

Hi everyone, I'm currently working on learning sails.js. I've been following some tutorials that mention the presence of a "views" directory in the default setup of a sails.js application. However, my setup does not have this directory. To addr ...