1

I have a document in my collection:

{
"_id" : ObjectId("5b8aaaebf57de10e080c9151"),
"user_email" : "temp@temp.com",
"platforms_budget" : [ 
    {
        "_id" : ObjectId("5b8aaaebf57de10e080c9154"),
        "platform_id" : "f_01",
        "platform_name" : "Facebook"
    }, 
    {
        "_id" : ObjectId("5b8aaaebf57de10e080c9153"),
        "platform_id" : "i_01",
        "platform_name" : "Instagram"
    }, 
    {
        "_id" : ObjectId("5b8aaaebf57de10e080c9152"),
        "platform_id" : "f_02",
        "platform_name" : "Facebook_Adds"

    }
],
"__v" : 0

}

I want to find specific user by "user_email" and get the length of the relevant "platform_budget" array. Which in this case suppose to be length=3.

My function is like this:

var BudgetSchema = require('../models/Budget');

  router.post('/temp', async function (req, res) {
  var length = await BudgetSchema.aggregate(
    [{ $match: { user_email: "test@test.com" } }, { $unwind: "$platforms_budget" },
    { $project: { "platforms_budget.count": { $size: '$platforms_budget' } } }])

  console.log(length);
})

When I try to console.log(length) I get an empty array.

I saw other answers on stackoverflow like this one, but I still can't understand what am I doing wrong or how to extract the size from the responce.

How do I get "platforms_budget" array size? Thank you.

Community
  • 1
  • 1
gusya59
  • 45
  • 7

1 Answers1

0

Assuming that ../models/Budget exports a Model, the Model#aggregate(Array, Function) expects the pipeline with aggregations as an array and an optional callback function that is passed an error (if any) and the result (if any).

.aggregate([...], function(error, resource) {
    // do what you want here
});

Or what you can also do is use the Aggregate object itself and invoke .exec(Function) on it where the function is a callback as well.

.aggregate([...]).exec(function(error, resource) {
    // do what you want here
});

I personally am still a bit confused about the documentation of .aggregate(Array, Function).

If a callback is passed, the aggregate is executed and a Promise is returned. If a callback is not passed, the aggregate itself is returned.

It sounds like if a callback is passed a promise is still returned but I couldn't find any evidence of any promise being returned by .aggregate(Array, Function) on GitHub at all.

Julian
  • 837
  • 1
  • 11
  • 24