Issue with MongoDB aggregate() - receiving error message: "TypeError: Cannot execute forEach method on undefined"

Here is the script I have in "script.js"

conn = new Mongo();
db = conn.getDB("learn");
db.contracts.aggregate([
  { $match: { regionCode: '77' } },
  { $unwind: '$products' },
  { 
    $project: {  
      _id: '$_id',
      regNum: '$regNum',  
      prodName: '$products.name',  
      prodPrice: '$products.price'
    }
  },
  { $match: { 'prodName' : 'Water' } }
], {cursor:{}}).result.forEach(printjson);

To run it, I use the command prompt in the following way

mongo script.js >> out.txt

The output in the "out.txt" file shows an error message

TypeError: Cannot call method 'forEach' of undefined at script.js

I face the same issue when running the script from the mongo shell using mongo.exe (using load()).

However, when executing the same aggregate command from Robomongo 0.8.4, I get successful results (3 documents in json format). Any idea why this inconsistency occurs?

Mongodb version 2.6.5

Answer №1

To successfully execute the code provided, make sure to remove any reference to the result variable. The cursor object returned by MongoDB in the shell does not contain a property called result, causing an error when trying to access it.

db.sales.aggregate([
  { $match: { regionCode: '77' } },
  { $unwind: '$products' },
  { 
    $project: {  
      _id: '$_id',
      regNum: '$regNum',  
      prodName: '$products.name',  
      prodPrice: '$products.price'
    }
  },
  { $match: { 'prodName': 'Water' } }
], { cursor: {} }).forEach(printjson);

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 implementing jQuery AJAX, remember to properly encode script tags to prevent any

Looking for a way to avoid script tags in content loaded through AJAX? Check out this approach: $.ajax({ cache: false, type: 'GET', url: 'index.html', success: function(response) { $(response).find('<sc ...

Is there a way to verify if all the values in an array of objects are identical?

In this scenario, my array consists of entries with identical address IDs but different phone types and numbers. I am in need of assistance with iterating through the array to extract the phone type and number when the address ID matches. I seem to encount ...

Customize a CSS attribute within Dojo

I am currently working with the enhanced grid in Dojo 1.10 version and I have encountered a simple problem that I am struggling to fix. I need to set a background-color CSS property for a table row, but there is already another background property applied ...

Running a Node JS application concurrently with an Express API connected to MongoDB

Here's my current project plan: I've created a small Node app that fetches data about the stock market from an API and then stores the data in a Mongo DB (which is already up and running). My next step is to create an API that will allow other se ...

You were supposed to provide 2 arguments, but you only gave 1.ts(2554)

Hey everyone, I hope you're having a good morning. Apologies for the inconvenience, I've been practicing to improve my skills and encountered an issue while working on a login feature. I'm trying to connect it to an API but facing a strange ...

Show the current date and time, and update it whenever the user chooses a different one

I need help with displaying the current date and time within a div, with the seconds refreshing when the page loads and changing when the user selects another date and time from the picker. I'm trying to accomplish this with the following script, but ...

MUI Step Indicator Icon is not visible

I'm having trouble getting the MUI Stepper Component to display Icons within each step node. Despite following the sample code provided by MUI, my implementation only shows a blank screen instead of the desired look. The desired appearance includes i ...

Please ensure to refresh the page after confirming the alert box by clicking OK

Is it possible to clear certain inputs on my Magento store's checkout page when an alert box is displayed and the user clicks OK? Unfortunately, I do not have control over the JavaScript alert. Therefore, I thought of implementing a script that can d ...

Encountered an issue while mapping to Firestore: Error message says the value for the argument "data" is not a valid Firestore document. The input does not appear to be a plain JavaScript object

I am attempting to assign a map variable value in JavaScript to a Firestore document as a map field using a cloud function. Unfortunately, it fails with the following error message: "Error: Value for argument 'data' is not a valid Firestore docum ...

What's the best way to pair a number with a neighboring letter?

const userInput = "2a smith road"; const secondInput = "333 flathead lake road, apartment 3b" const formattedAddress = userInput.replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase()); The final result will ...

retrieve information based on specific criteria in strapi

I am currently developing an API using Strapi and I've encountered a specific situation where I need to fetch data. The requirement is to retrieve records where the audience_name is similar to '%audienceName%' and created_by is equal to 4 ...

Display the output from a JavaScript code snippet on the console

Is there a simple way to incorporate JavaScript into RMarkdown and display the results in the knitted document without adding a lot of extra code? I discovered that I can create new div elements and attach them to the document's DOM, but this method s ...

Evaluating CSS performance: Comparing the animation of a floating button's size on scroll using transform scale versus adjusting height and width

Initial details: In order to display the navigation menu effectively on mobile devices, I have created a fixed menu button. To enhance user experience, I am using the Headroom.js script to reduce the size of the button when scrolling down, preventing it fr ...

Utilize AngularJS to dynamically generate a page corresponding to the selected option

Looking for assistance with displaying content based on selected option from a dropdown list. SAMPLE HTML CODE: <label class="col-md-0" for="Role"> <br>Role: </label> <select name="role" id="roleType"> <option value="A" ...

What is the best way to iterate over a collection of JSON objects?

Currently, I am facing an issue with looping through JSON data stored in a file named "people.json". The structure of the file is as follows: [{"firstname":"John","lastname":"Smith","age":"40"},{"firstname":"Bill","lastname":"Jones","age":"40"}, ...] My ...

A guide on implementing Google reCAPTCHA in a Nuxt.js website

Trying to implement the recaptcha-module from nuxt-community in my Nuxt project but struggling with verifying if the user has passed the check. The documentation and example provided are not clear enough for me (https://github.com/nuxt-community/recaptch ...

Tips on scrolling down to find the text you're looking for

I attempted to scroll downwards in my application's window using the following JavaScript code: ((JavascriptExecutor) driver).executeScript("windows.scrollBy(0,500)"); Additionally, I tried to ensure a specific element is in view with this script: ...

Adding extra fields to an existing JSON response in a TypeScript REST API

I am in need of an additional column to be added to my response data. Currently, I am fetching data from multiple REST endpoints one by one and merging the results into a single JSON format to display them in an Angular Mat table. The columns that I want t ...

Animation displayed on page load before running

Is there a way to ensure that my animation runs smoothly without any lag or jankiness, either while the page is loading or immediately after loading? I have attempted to preload the images using a preload tag in the header of my HTML, but unfortunately, t ...

A step-by-step guide on accessing an expressjs endpoint from a static html file using Vercel

I am working on a basic app that consists of one server named /api/index.js and one file called index.html located at the root. In the index.js file, there is a route defined as app.get("/api/mystuff", () => {...}) The index.html file makes a request ...