Result is not defined after aggregating in MongoDB with Mongoose framework

I am struggling to retrieve comments from a MongoDB collection (using Mongoose) and compute the total number of comments as well as the average rating using the aggregate pipeline. However, if the initial $match query returns no results, the script crashes and displays a 'Cannot read property 'avg' of undefined' error.

    var q = Comment.aggregate([
    { $match: {
        _post: this,
        rating: { $gt: 0 },
    }},
    { $group: {
        _id: null,
        avg: { $avg: "$rating" },
        count: { $sum: 1 }
    }}
]);

q.exec(function(err, result) {
    cb(err, result[0].avg, result[0].count);
});

If I eliminate the _post $match condition, the output shows the correct average and count of all comments. However, if $match does not return any records, an error is thrown. How can this be resolved?

Answer №1

It turns out my mistake was looking in the wrong location. The error message wasn't related to the 'avg' in the query, but actually to result.avg within the callback function. Right before I posted, I updated the callback function parameters to result[0].avg, which resulted in a new error message stating it couldn't read '0' from undefined.

I focused too much on the incorrect area and ended up posting prematurely.

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

Attempting to redeclare a previously exported variable will result in an error stating: "Cannot

I'm currently facing an issue with a npm module located in a different directory that I've linked to another project using npm link. Despite successfully compiling the typescript, when I try to import the module and use its function, I encounter ...

Typescript compiler still processing lib files despite setting 'skipLibCheck' to true

Currently, I am working on a project that involves a monorepo with two workspaces (api and frontEnd). Recently, there was an upgrade from Node V10 to V16, and the migration process is almost complete. While I am able to run it locally, I am facing issues w ...

Utilizing two nearby node servers to route traffic according to designated paths

I am seeking a solution to achieve the following: There are two servers running locally on different ports: localhost:3001 localhost:3002 I want a third server on port 3000 to route all traffic to localhost:3001 except for specific paths that are white ...

Determining If a setInterval Function is the Sole Factor Preventing an App from Exiting

Is there a method to determine the number of tasks remaining for Node before it automatically exits because all tasks are completed? I am interested in utilizing setInterval but only while the application is still running other processes. I do not want t ...

Issue with GitHub API: The "Get contents" function is consistently returning a 404 error even for valid paths

I've recently started using probot, which can be found at Currently, I am in the process of developing a GitHub application that is designed to analyze a specific .json file within a repository for any changes to date strings. To achieve this, I have ...

The try/catch block proves ineffective at handling a socket connection exception

I am attempting to test connection to a non-existent socket. In this scenario, an exception is thrown and I anticipate it being caught in the try/catch block below. The function createConnection is imported from the net package. try { createConnection( ...

Top method for managing missing sub-documents in MongoDB query outcomes

I've seen this question asked in various forms before, but I'm seeking the most efficient way to manage query results without relying on multiple if statements. Imagine I need to locate a product (sub-document) within a package (document) Packa ...

Difficulty Establishing a Connection with SQL Server Using TypeORM

My local machine is running an SQL Server instance, but I'm encountering an error when trying to connect a database from TypeORM. The error message reads: originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (seque ...

Updating JSON in JavaScript

I am striving to structure a JSON object in the following manner: {"tokenId":1,"uri":"ipfs://bafy...","minPrice":{"type":"BigNumber","hex":"0x1a"},"signature":"0 ...

Attempting to showcase the data stored within MongoDB documents on my website's user interface

I am facing difficulties in showing the data stored in my database on the front end of my grocery list app, which is built using the MERN stack. I have a form that successfully sends data to MongoDB and saves it upon submission. In order to retrieve the d ...

Comparison between belongsTo and hasMany associations in Sequelize

Consider a scenario where we have a "shirt" table and a "john" table. When using Sequelize, if we define db.john.hasMany(db.shirt), a foreign key is created in the "shirt" table. Similarly, when we use db.shirt.belongsTo(db.john), a foreign key for "joh ...

When processing a response from the backend (using express js), cookies are not being received in the browser while on localhost

I'm currently facing some difficulties with implementing authorization cookies within my application. Whenever I attempt to send a GET request to my API (which is hosted on port 8080) from my React frontend (running on port 3000), the cookies that I ...

Setting up a Node.js WebSocket server on a shared cPanel hosting environment

Recently, I obtained a shared hosting plan with cPanel support for nodejs applications. Through the "Setup Node.js App" feature, I am able to define and set up a node.js app on my server. My goal is to create a websocket, and fortunately, they have opened ...

Having issues with angular-file-upload failing to include the file in the request

I am currently using angular-file-upload in order to upload an image to a server that is utilizing Node and Express 4.0. However, I am encountering difficulties in accessing the file data on the server. Below is the relevant code snippet: <input type= ...

Is it advisable to create a separate MongoDB connection for each thread in my application?

Is it more efficient to establish a connection to MongoDB using the Node.js cluster library in the master thread or in each child thread? Can multiple threads share the same connection? Considering performance, would it be better to use a single shared c ...

Tips for executing an asynchronous function in a synchronized manner within a Node.js environment

Currently, I am utilizing the Express framework. The issue that I am encountering involves a variable called 'duration'. Whenever a request is made to '/', the total duration of a given video is calculated and saved to this variable. H ...

Issue encountered while using node-pre-gyp to install sqlite3

Recently at my workplace, we encountered an interesting challenge involving a Website (WIP) that retrieves data from an SQLite Database. Since the website is built using Javascript as its Backend, we decided to experimentally install sqlite3 on the server ...

Having difficulty navigating through the dependency tree due to eslint-config-airbnb

When attempting to install eslint-config-airbnb using npx install-peerdeps --dev eslint-config-airbnb, I encounter the following error (using the --legacy-peer-deps flag doesn't resolve it): npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! ...

A Comprehensive Guide on Incorporating Nodejs Modules in a Subdirectory

Within my AWS Lambda layer, I have a directory structure that resembles the following: main > nodejs > node_modules Prior to uploading to AWS, I require a test.js file for functionality testing purposes. The question at hand is whether it's fe ...

Using the _id String in a GraphQL query to retrieve information based on the Object ID stored in a

Encountering an issue with my graphql query not returning anything when sending the _id as a string. Interestingly, querying the DB using any other stored key (like name: "Account 1") works perfectly and returns the object. I've defined my Account sch ...