How to implement dynamic aggregate functions with parameters in Express and Mongoose

I have implemented an aggregate function in mongoose to fetch some data, with a static implementation.

app.get("/male",function (req,res) {
  Record.aggregate([
    {
      $match: 
      {"gender": "male"}
    },
      {
         $group:{ 
            _id : "$type",
             total : {$sum : 1}
        }
      },{
      $sort: {_id: 1}
    }
      ]).exec((err,data) => {
            if (err) {console.log(err)} 

            res.json(data)

        })

})

I wanted to make it completely dynamic so I attempted the following:

  app.get("/:query/:type/:match",function (req,res) {

  var match = req.params.match

  Record.aggregate([
    {
      $match: 
      {match : req.params.type}
    },
      {
         $group:{ 
            _id : "$"+req.params.query,
             total : {$sum : 1}
        }
      },{
      $sort: {_id: 1}
    }
      ]).exec((err,data) => {
        if (err) {console.log(err)}

              res.json(data)

        })

})

Upon debugging, it seems that match is not being passed in $match.

If I replace 'match' with a static variable, it works.

Here's the schema:

   var mongoose = require('mongoose');

   var RecordSchema = new mongoose.Schema({

      type:String,
      gender:String,
      age:Number,
      timeSpent:Number,
      arrivedAt:Number

   })

   module.exports = mongoose.model("Record", RecordSchema);

Answer №1

Give this method a try:

app.get("/:category/:genre/:filter",function(req,res) {

  var filter = req.params.filter;
  var genre= req.params.genre;
  var category = "$"+req.params.category;
  var filterCriteria = {};
  filterCriteria[filter]=genre;


  Entry.aggregate([
    {
      $match:filterCriteria
    },
    {
         $group:{ 
             _id : category,
             total:{$sum:1}
        }
    },{
      $sort: {_id: -1}
     }
   ]).exec((err,result) => {
        if (err) {console.log(err)}
              res.json(result)
        });
});

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

The 'fn' argument passed is not a valid function, instead it is a string

I am encountering an issue while trying to retrieve data from my server. The console doesn't provide any specific information about the error. My objective is to fetch JSON data from the server and use it to display the required information. I am util ...

What is the best way to bind a model to a directive in Angular.js?

I have been experimenting with different methods to create a two-way binding between my directive and repeater, but so far I haven't been successful. Although I have tried various strategies suggested online, the current setup does not pass item.myDat ...

Having trouble with adding an event listener on scroll in React JS. Need assistance in resolving this issue

I'm having trouble adding an event listener for when a user scrolls in my web app. componentDidMount = () => { let scrollPosition = window.scrollY; let header = document.getElementById("topBar"); window.addEventListener(&ap ...

Setting up Mongoose with Admin JS in NestJS: A Step-By-Step Guide

After successfully configuring adminJS in my Nest JS application, it now runs smoothly on localhost:5000/admin. @Module({ imports: [ import('@adminjs/nestjs').then(({ AdminModule }) => AdminModule.createAdminAsync({ ...

Is jQuery validation compatible with mobile phone numbers?

Is there a way to verify an Iranian mobile phone number using jQuery with the input:text? Iranian mobile phone numbers follow a specific numeral system, such as: 091- --- ---- 093[1-9] --- ---- 092[1-9] --- ---- 090[1-9] --- ---- Here are some example pr ...

Tips for managing the ever-evolving language state in expressJS

I am currently working on a project utilizing nodeJs, handlebars, and the expressJs framework. I have implemented a language change functionality using the i18n-express module. This module adds a query string at the end of the URL when changing languages. ...

FingerprintJS is experiencing an issue with the navigator object not being defined, resulting in

I am currently working on extracting browser fingerprint using fingerprintjs2, an npm package in Javascript. However, I encountered the following error: ReferenceError: navigator is not defined Error Logs: Code Snippet: const Fingerprint = require(&apo ...

What is the proper way to input a Response object retrieved from a fetch request?

I am currently handling parallel requests for multiple fetches and I would like to define results as an array of response objects instead of just a general array of type any. However, I am uncertain about how to accomplish this. I attempted to research "ho ...

Loading V-Select with Data from JSON Using Vue.js

I tried to populate my v-select multiselect element using a JSON object, but unfortunately it did not work as expected. Here is the result I encountered: <v-select v-model="serviceValues" :items="serviceOptions" item-text="se ...

Tips for displaying an alert after a successful form submission and ensuring user input validation

I created a form with PHP code to send emails, but I'm struggling to add an alert without page refresh upon submission. The alert needs to display in green or red text below the button. Validation for email input is needed, as well as protection again ...

Modifying an item within an array of Mongoose models

I am working with a model schema that looks like this: { _id: foo cart: { items: [ { id: number name: string, } ] } } My goal is to locate the document by its id and then modify the name value of the object in ...

Delay the loading of JavaScript libraries and multiple functions that are only executed once the document is

After learning how to defer the loading of JS libraries and a document ready function from this post, I encountered a challenge. The code I currently have handles multiple document ready functions inserted by different modules, not on every page. echo&ap ...

Making a Call with Twilio using Node.js

Currently, I am working on a click-to-call website that is powered by Twilio. The process involves configuring a TwiML app and writing Twilio JavaScript SDK client-side to send requests to Twilio. Once this is done, Twilio will initiate a POST request to t ...

Exploring properties of nested elements in React

Picture a scenario where a specific element returns: <Component1> <Component2 name="It's my name"/> </Component1> Now, what I want to accomplish is something like this: <Component1 some_property={getComponent2'sN ...

Retrieve a specific line of code from a snippet of JavaScript

I am looking to extract a specific line of code from a script that I am receiving via ajax... The line in question is new Date(2010, 10 - 1, 31, 23, 59, 59) found within the following snippet: jQuery(function () { jQuery('#dealCountdown').count ...

What is the best way to retrieve calendar events using Microsoft Graph and NodeJS based on the calendar name?

Is there a way to condense these two API calls into one? Currently, this code uses microsoft-graph-client to first retrieve the ID of a specific calendar and then fetch the events from that calendar. I am looking for a method to combine these into a single ...

At the beginning of the application, access the Ionic Secure Storage using the get() method

I am facing an issue with retrieving a token for validating an Auth status in the /src/main.ts file: if (TokenService.getAccessToken() !== undefined) { ... } Here is my token.service.ts file: import storage from '@/plugins/storage' const ACCESS ...

Trustpilot Authentication Error: Grant_type Not Recognized

I am attempting to utilize the Trustpilot API for sending email review invitations. Before making the call, I need to obtain an access token as per Trustpilot's documentation. However, when implementing the function below, I am encountering an error i ...

Reduce the length of the text to 50 characters after the current word, while ensuring that the word

Looking for a way to shorten text after reaching 50 characters, making sure not to split words in the middle when cutting off. For example: Contrary to popular belief, Lorem Ipsum is not simply text (59 chars) Desired output: Contrary to popular belief, ...