Search code examples
node.jsmongodbmongoosenode-modulespipeline

How to return the result of a mongodb pipeline by a get methodo?


I have a pipeline and its result I want to return it by an express method that is get or not i know if it is more advisable to send it by a socket

this is my file pipeline.js:

function getModel(model) {
     model.aggregate([{
         $group: {
             _id: null,
             "price": {
                 $sum: "$price",

             }
         }
     }]).exec((e, d) => {
         return JSON.stringify(d)
     })
 }

 module.exports = getModel;

in the model.js file I'm going to call my pipeline.js file and therefore the function

model.js:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const getModel = require('./pipeline');
const mySchema = new Schema({
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    namepet: String,
    type_of_service: String,
    characteristic_of_pet: String,
    price: Number

});

const model = mongoose.model('Cites', mySchema);
here is the function-> getModel(model);

module.exports = model;

and it works for me as I want the problem is that the result I have to send it by a method get and I have no idea how to do it

enter image description here

How can I send the result indicating the red arrow of the image by a get method?


Solution

  • var express = require('express');
    var app = express();
    
    
    function getModel(model) {
      model.aggregate([{
        $group: {
          _id: null,
          "price": {
            $sum: "$price",
    
          }
        }
      }]).exec((e, d) => {
        return JSON.stringify(d)
      })
    }
    app.get('/', function(req, res) {
      console.log('marhaba');
      res.send(getModel( ** Model ** ))) //== > here call the getModel function
    });
    
    
    app.listen(3000, function() {
      console.log("Working on port 3000");
    });