Calculating the size of an array of objects using Mongoose's aggregate function

I have a specific document in my collection that I need help with:

{
"_id" : ObjectId("5b8aaaebf57de10e080c9151"),
"user_email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9cddcd4c9f9cddcd4c997dad6d4">[email protected]</a>",
"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

}

My task is to locate a specific user using their email address under "user_email" and determine the length of the associated "platform_budget" array. In this instance, the expected array length is 3.

The function I am utilizing for this task is shown below:

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

router.post('/temp', async function (req, res) {
var length = await BudgetSchema.aggregate(
[{ $match: { user_email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bacedfc9cefacedfc9ce94d9d5d7">[email protected]</a>" } }, { $unwind: "$platforms_budget" },
{ $project: { "platforms_budget.count": { $size: '$platforms_budget' } } }])

console.log(length);
})

Upon attempting to log the value of length, an empty array is returned.

I have reviewed similar solutions on websites like this one, but I am still unable to grasp what mistake I am making or how to access the size information from the response. Can anyone assist me in determining the size of the "platforms_budget" array?

Your guidance is greatly appreciated.

Answer №1

When ../models/Budget exports a Model, the Model#aggregate(Array, Function) function requires the pipeline with aggregations in an array format, along with an optional callback function that handles any errors and results.

.aggregate([...], function(error, result) {
    // handle actions here
});

Alternatively, you can also utilize the Aggregate object directly and use .exec(Function) method with a callback function.

.aggregate([...]).exec(function(error, result) {
    // handle actions here
});

I still find the documentation regarding .aggregate(Array, Function) a bit confusing.

If a callback is provided, the aggregate operation is executed and a Promise is returned. If no callback is provided, the aggregate itself is returned.

The statement seems to suggest that a promise is returned when a callback is used, but I could not locate any evidence of a promise being returned by .aggregate(Array, Function) on GitHub.

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

When working in Node, leverage the `then()` method to execute functions sequentially

Is there a way to run a loop function synchronously rather than asynchronously without using callbacks or external libraries? File 1 var db = require('./promiseUnderStanding'); var fun = function () { for (var i = 0; i < 10; i++) { ...

Content inside div tags fails to display upon clicking

I've encountered an issue where I'm attempting to show the data within a dynamically generated div tag when a href link is clicked. However, the div tag does not seem to be responding as expected. This problem occurs in a .tpl file with the follo ...

Is the Angular $watch function able to track changes on an object's prototype members as well?

I have encountered a challenge with a tree structure implemented in Javascript which has circular references. The objects in the structure contain an array of children, but these children also need to reference their parent for deletion purposes. To monit ...

When using findOneAndUpdate to modify specific elements within an array, the Mongoose library is failing to update the booleanValue field in the array

Updating a boolean value in an object within an array in a mongo document using mongoose is proving to be tricky. app.post("/api/post/:chorecomplete", function(req, res){ Parent.findOneAndUpdate({parentFirstName: req.body.parentFirstName, parentLastN ...

`Troubleshooting Firebase Cloud Functions and Cloud Firestore integration`

I previously used the following Firebase Database code in a project: const getDeviceUser = admin.database().ref(`/users/${notification.to}/`).once('value'); Now, I am attempting to convert it for Firestore. My goal is to retrieve my users' ...

A guide on extracting and converting strings in React to display as HTML

I am in the process of developing a simple blog app using a MERN stack. Currently, I have the functionality to create posts with just plain text. Is there a way to incorporate HTML rendering within the content of these posts? For example, a post might con ...

Mongoose encountering blank value

Hey, I'm encountering an issue with my schema where the values I pass are showing up as empty and required. It's confusing to me why this is happening. Model.js:- var adminSchema = new mongoose.Schema({ companyName : { type: ...

Enhance each category changing with jQuery page transitions

Is there a way to add page transitions based on category names and quantities in PHP? For example, when clicking on the "office" category, can a popup overlay be displayed with the category name and quantity while the content loads? The focus is on creat ...

Determine the width of the uploaded image upon completion of the upload process with the help of the

After uploading an image using uploadify, I need to determine its width so that I can ensure it maintains the correct proportions with the previous one. OBJECTIVE: Determine the WIDTH of the uploaded image ...

Encountering issues with Materials UI DataGrid: errors thrown and data not visible on display

Struggling to implement the DataGrid component from Material-UI, I've been following their examples but encountering JS errors. Failed prop type: Invalid prop 'modifiers' of type 'array' supplied to 'ForwardRef(Popper)', ...

Is it possible to encounter the issue of "Context Lost" and "Importing multiple instances" in Three.js?

I am in the process of developing a 3D editor that allows users to manipulate a 3D scene and then view the result by pressing a "play" button. In order to display the output, I am utilizing an iframe. Below is the snippet of my HTML code: <iframe id=&qu ...

The command "npm run build:css " is not functioning properly, but when I execute the script independently, it works fine

Recently, while working on a program using npm script on my Mac system, I encountered some issues. Despite having installed node-sass globally, running "npm run build:css" did not work as expected. The content of my package.json file can be viewed here. Th ...

Discovering products that are on the brink of expiration using MongoDB Aggregation

Can you assist me in locating products that will expire in 3 days, have a remaining stock greater than zero and utilize the given aggregation pipeline? db.products.aggregate([ { $lookup: { from: "stocks", let: { stock ...

Utilize separate production environments for each client on the NodeJS server to ensure seamless operation and

After conducting extensive research, I have been unable to find a solution to my current problem. I am operating a Node server with multiple environments (dev, test, demo, prod). The server is deployed on a Linux server in the production environment via a ...

How can I extract the initial values from PHP after receiving the JSON + serialized data in the Ajax response following the first submission?

I am currently utilizing ajax to store data for multi part forms. My goal is to save each form's data upon clicking the next button. I have utilized form data to serialize the information, however, the format of the data is not aligning with my expect ...

Can you customize the first element within a span tag using a for loop?

I am having an issue where only the last element in a span is being set within a for loop. The code is functioning correctly, but I want to ensure that the first element is the one set as cust_name. success : function(data) { co ...

Struggling with using jQuery to generate link tags and combine the href attribute to save the result as a variable

For this purpose, I initialized a variable called link to hold the link's information like this: var link = '<li>' + '<a href="vote.php?id=" + result + '>' + '<b>' *text goes here* + '</b&g ...

Struggling to generate package using manifoldjs

Excited to dive into the new tool called ManifoldJS introduced by Microsoft at Build 2015, I'm facing some challenges. My website is up and running as a basic HTML- and JS-based app using Angular and TypeScript. I've even created a manifest.json ...

Issue with Puppeteer in Node.js causing if/else statements to not work as expected

const found = await page.waitForSelector('[name="commit"]'); if (found) { await page.click('[name="commit"]'); console.log('Clicked successfully'); } else { await browser.close(); console.log('Selector not ...

Jade: utilizing a Jade block within a Mixin by passing it as a string

I have come across a Jade template that includes a call to a mixin at a specific point. One of the parameters passed to this mixin is a lengthy HTML string which the mixin then prints using != The code looks like this: +createHTML({firstSection:'< ...