How to use fill functions by filling or creating an internal query with aggregation in mongodb

I have the following data in mongod.

 {
            "_id" : ObjectId("54a0d4c5bffabd6a179834eb"),
            "is_afternoon_scheduled" : true,
            "employee_id" : ObjectId("546f0a06c7555ae310ae925a")
 }

I would like to use populate with aggregate and want to get full information about the employee in the same answer, I need help with this. My code is:

var mongoose = require("mongoose");
var empid = mongoose.Types.ObjectId("54a0d4c5bffabd6a179834eb");
Availability.aggregate() 
    .match( { employee_id : empid} )
    .group({_id : "$employee_id",count: { $sum: 1 }})
    .exec(function (err, response) {
        if (err) console.log(err);
            res.json({"message": "success", "data": response, "status_code": "200"});
        }
);

The answer I get is

{"message":"success","data":{"_id":"54a0d4c5bffabd6a179834eb","count":1},"status_code":"200"}

Expected Answer:

{"message":"success","data":[{"_id":"54aa34fb09dc5a54232e44b0","count":1, "employee":{fname:abc,lname:abcl}}],"status_code":"200"}
+4
source share
2 answers

This works as an application fill using an aggregate using an internal query.

   var mongoose = require("mongoose");
    var empid = mongoose.Types.ObjectId("54a0d4c5bffabd6a179834eb");
    Availability.aggregate() 
        .match( { employee_id : empid} )
        .group({_id : "$employee_id",count: { $sum: 1 }})
        .exec(function (err, response) {
            if (err) console.log(err);
            if (response.length) {
                     var x = 0;
                    for (var i=0; i< response.length; i++) {
                          empID = response[i]._id;
                          if (x === response.length -1 ) {
                          User.find({_id: empID}, function(err, users){
                            res.json({"message": "success", "data": users, "status_code": "200"});
                          });
                          }
                          x++;
                    }
            }
        }
    );
-1
source

.populate() . , "", , .

, :

var async = require('async'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;


var employeeSchema = new Schema({
  "fname": String,
  "lname": String
})

var availSchema = new Schema({
  "is_afternoon_scheduled": Boolean,
  "employee_id": {
    "type": Schema.Types.ObjectId,
    "ref": "Employee"
  }
});

var resultSchema = new Schema({
  "_id": {
    "type": Schema.Types.ObjectId,
    "ref": "Employee"
  },
  "count": Number
});

var Employee = mongoose.model( "Employee", employeeSchema );
var Availability = mongoose.model( "Availability", availSchema );
var Result = mongoose.model( "Result", resultSchema, null );

mongoose.connect('mongodb://localhost/aggtest');

async.series(

  [
    function(callback) {
      async.each([Employee,Availability],function(model,callback) {
        model.remove({},function(err,count) {
          console.log( count );
          callback(err);
        });
      },callback);
    },

    function(callback) {
      async.waterfall(
        [
          function(callback) {
            var employee = new Employee({
              "fname": "abc",
              "lname": "xyz"
            });
            employee.save(function(err,employee) {
              console.log(employee),
              callback(err,employee);
            });
          },
          function(employee,callback) {
            var avail = new Availability({
              "is_afternoon_scheduled": true,
              "employee_id": employee
            });
            avail.save(function(err,avail) {
              console.log(avail);
              callback(err);
            });
          }
        ],
        callback
      );
    },

    function(callback) {
      Availability.aggregate(
        [
          { "$group": {
            "_id": "$employee_id",
            "count": { "$sum": 1 }
          }}
        ],
        function(err,results) {
          results = results.map(function(result) {
            return new Result( result );
          });

          Employee.populate(results,{ "path": "_id" },function(err,results) {
            console.log(results);
            callback(err);
          });
        }
      );
    }


  ],
  function(err,result) {
    if (err) throw err;
    mongoose.disconnect();
  }

);

, , , :

        function(err,results) {
          results = results.map(function(result) {
            return new Result( result );
          });

          Employee.populate(results,{ "path": "_id" },function(err,results) {
            console.log(results);
            callback(err);
          });
        }

, , - , , .aggregate(), mongoose, .find(). , , . , Result, .

.populate() Employee results "" .

- , Employee, .

[ { _id:
     { _id: 54ab2e3328f21063640cf446,
       fname: 'abc',
       lname: 'xyz',
       __v: 0 },
    count: 1 } ]

, find, " " - , .

+4

Source: https://habr.com/ru/post/1570112/


All Articles