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

Massive HTML Table Containing Rows upon Rows

Currently, I have a server that can provide me with a list of objects in json format, and my goal is to showcase them in a table on the client side. Initially, I thought about dynamically modifying the DOM after receiving data from the server. Building th ...

Updating inner text content dynamically can be accomplished without relying on the use of the eval() function

I am faced with a situation where I have multiple batches of code structured like this: 1 <div id="backgrounds" class="centery">Backgrounds 2 <div id="bk1" class="attr">Background 1 3 <div class="container"> 4 ...

Tips for sending an email to an address from a user input field in React.js/Express.js

I am currently developing an email application that allows users to send emails to any recipient of their choice. The challenge I'm facing is that I need a way to send emails to user-specified email addresses without requiring passwords or user.id det ...

What is the best way to show an SVG icon in React without having to make an HTTP request for the file?

A special requirement for a react application is to display icons in certain parts of the application while offline. The use of inline svg is particularly fitting for this purpose. import React from 'react'; // Utilizing inline svg to showcase i ...

Unable to utilize a computed property within the data section

I am working with an array in my data: data () { return { steps: [ { disabled: this.someCheck } ] } } Additionally, I have a computed property: computed: { ...mapGetters({ getFinishedSteps: 'jobFound/getFinishedS ...

The appearance of SVG markers varies depending on the screen they are viewed on

Latest Update: I have finally figured out the screen issue. The device pixel ratio is to blame. Icons appear smaller on devices with lower window.devicePixelRatio. One solution I found is to adjust the icon size based on window.devicePixelRatio, like this ...

Facebook and the act of liking go hand in hand, growing together

I am working on a website where I want to include Facebook like and share buttons with counters. To achieve this, I used Facebook's own links to generate these buttons for the specific URL. The issue I encountered is that when I like or share the page ...

Is employing setTimeout a legitimate technique for circumventing a stack overflow issue when implementing callbacks?

Let's imagine a scenario where I deliberately create a complex sequence of callbacks: function handleInput(callback) { ... } function fetchData(url, callback) { ... } function processResponse(callback) { .... } function updateDatabase ...

Error encountered in NodeJS: Promise TypeError - res.json is not a function while handling pre-signed URLs. This results in

I'm having trouble generating a list of pre-signed URLs for files in my private S3 bucket. Despite researching similar issues on multiple forums, I can't seem to resolve the error with the res.json function in my code. Can someone please help me ...

Is it possible to achieve livereload with gulp.js on an express server?

I've been struggling to configure my gulpfile.js for livereload on an express server. Most examples I find are for static file servers. Here are some resources I've looked at: In my app.js, I have the standard express server setup with Jade fil ...

ng-repeat to display items based on dropdown choice or user's search input

Utilizing $http to retrieve JSON data for display in a table. I have successfully implemented a search functionality where users can search the JSON data from an input field. Additionally, I now want to include a feature that allows users to filter the JSO ...

Using this PHP function

I am facing an issue with a table that contains some information. I want to be able to click on a specific row (e.g. the second row) and display all the corresponding database information. However, I am unsure how to achieve this using the $this function ...

I'm having an issue with my NextJS timer where it doesn't stop and ends up going into negative numbers. Any

Here is the code snippet for my timer component. It fetches the 'createdAt' prop from the database and functions correctly. However, I have encountered an issue where the timer does not stop at 0 but continues running indefinitely. I attempted to ...

"Utilizing JavaScript to Disable a MenuItem in ASP .NET: A Step-by-Step

I have successfully designed a customized menu interface using ASP.NET. <asp:Menu ID="Name1" runat="server" OnMenuItemClick="DoSth_MenuItemClick" Visible="true"> <Items> <asp:MenuItem Text="Function description" Value="Val" ToolTip=" ...

organizing strings in alphabetical order using TypeScript

My md-collection is set up to display a list of emails like this: <md-collection-item repeat.for="u of user" class="accent-text"> <div class="row"> <di ...

Efficiently loading components in Angular using browserify with lazy loading

As I work on developing the architecture of a complex application with Angular, I have started with the angular-seed project which seems to be a solid starting point. However, one issue that concerns me is how Angular apps tend to load everything upfront b ...

Mongoose aggregate not returning any results

I'm currently working on using Mongoose aggregate to group businesses. I have a MongoDB script that is functioning properly. Below, you'll find the NodeJS code with Mongoose as well as the MongoDB code: History.aggregate() .cursor({ bat ...

"Encountering an issue with the parameter 'undefined' in the .find()

Recently, I've been facing some challenges while using the .find() method within a vuex getter. I initialized a store with a list under state (pages) // state.js const state = { pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}] }; In my ...

While Ajax POST is functional on desktop, it does not seem to work on Phonegap applications or Android

I am facing an issue with a global function that does not seem to work properly in the PhoneGap Desktop app or Chrome Mobile on Android. Surprisingly, it works perfectly fine only in the Chrome PC version. The function is called using an onClick event, a ...

`enable cookie sharing between subdomains with the combination of express and angularjs`

I've been struggling with a task for quite some time now without any success. I would greatly appreciate it if someone could assist me with this. Present Scenario: I have two applications running on two sub-domains: st.localhost:8080 and acm.loca ...