Querying MongoDB using JavaScript function

Currently, I am utilizing a MongoDB query within a JavaScript function. The script is structured as follows:

var continous = ['b', 'e', 'LBE'];

continous.forEach(e => izracun(e));

function izracun(atr) {
    var query1 = { "$match": { [atr]: {"$ne" : -1} } };
    var query2 = { "$group": { "_id": atr, "avg": { "$avg": "$"+[atr] }, "stdev": { "$stdDevPop": "$"+[atr] }, "nonMissing": { "$sum": 1 }}};

    db.ctg.aggregate([query1, query2]); 
}

Upon executing this script in the mongo shell using load("script.js"), the shell responds with "true". Even when I attempted to use fixed parameter values within the function instead of passing arguments, I did not achieve the expected results (only "true" is returned) which should resemble the example below:

{ "_id" : "b", "avg" : 878.4397930385701, "stdev" : 893.8744489449962, "nonMissing" : 2126 }

If I log the query and run it directly in the mongo shell, it functions correctly.

What could be the issue here?

EDIT: I attempted to manage the promise with:

db.ctg.aggregate([query1, query2]).then(function (results) { //this block will run synchronsly to the aggregate statement
    console.log(results);
}); 

However, I encountered the following error:

uncaught exception: TypeError: db.ctg.aggregate(...).then is not a function

Answer №1

When you execute the query, it returns a promise and continues to run asynchronously in the background while the remaining code proceeds. To receive an output, you can modify the code as shown below:

var continous = ['b', 'e', 'LBE'];

continous.forEach(e => calculate(e));

function calculate(atr) {
   var query1 = { "$match": { [atr]: {"$ne" : -1} } };
   var query2 = { "$group": { "_id": atr, "avg": { "$avg": "$"+[atr] }, "stdev": {"$stdDevPop": "$"+[atr] }, "nonMissing": { "$sum": 1 }}};

    db.ctg.aggregate([query1, query2]).then(function (results) { //this block will run synchronsly to the aggregate statement
        console.log(results);
    }); 
    console.log("after"); //<-- this will apear before the results do despite being after it
}

If you want the function to wait for the query to complete, you can explore async/await (https://javascript.info/async-await) or you can return the promise and handle it elsewhere based on the overall context of your code.

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

Error: The property 'title' is not defined and cannot be read

Javascript - Node.js - Express - MongoDB - Mongoose In my code, I am using a forEach() method that iterates through each user and manipulates an array by adding or removing items. Strangely, the method successfully adds the correct number of items for one ...

Getting PHP / JavaScript error popups to display in a visually appealing manner: tips and tricks!

I have a question that may be simple for many, but I'm struggling to find the answer: When an error message appears while processing a PHP or JavaScript script, the title is usually "The page at localhost [or another URL] says:". The contents often i ...

Select three unique numbers at random from the total number of elements in the array

I currently possess an array containing a variety of objects. At present, there are 21 objects in this array, although this number is subject to change. To iterate through the array and generate the necessary content, I am implementing the following code ...

Passing a complex variable type in TypeScript to a function without the need to redefine the type

I'm fairly new to working with TypeScript and I've encountered this issue several times. When using tools like Prisma to retrieve data, I often come across values with incredibly complex types. These values contain many attributes, which is perf ...

core.js encountered an issue at line 6210: TypeError - The function this.service.addDepartment does not exist

Whenever I attempt to click the 'Add' button on a web application that I'm constructing, an error pops up. core.js:6210 ERROR TypeError: this.service.addDepartment is not a function at AddEditDepComponent.addDepartment (add-edit-dep.componen ...

Starting data initialization using a property object within a Vue component

I am encountering an issue with two Vue components, EventTask and EventCard. Within EventTask, there is a currentEvent object in the data section, which I pass as a prop to EventCard using the following code snippet: <event-card :current-event="cur ...

ES6 syntax specification allows for the use of a fat arrow function for declaring React components

When learning React, I have noticed two different ways of declaring components. The first is using the classic fat arrow syntax with a return statement. const Component = () => { return ( <div>Hello</div> ) } Recently, I came ...

Does Jquery AJAX send back raw data or HTML ready for use?

I'm currently developing a mobile app using Jquery Mobile. In order to populate the app with data, I need to make requests to an API and display the information within the app. At this point, I have two possible options: The API returns JSON data ...

Dynamically binding image URLs in VUEJS

Below is the JSON data containing button names and their corresponding image URLs: buttonDetails= [ { "name": "button1", "images": [{ "url": "https://localhost:8080/asset/d304904a-1bbd-11e6-90b9-55ea1f18bb ...

The fullcalendar is experiencing difficulties in showing the event

I am facing an issue with Fullcalendar where the events fetched by ajax are not showing up on the calendar. Even though the events are successfully passed and can be displayed in a pop-up, they do not render on the calendar. When manually setting the event ...

When attempting to use Arabic characters in my PDF file with LIP, I encounter an error: "TypeError: font must be of type PDFFont or n, but was actually of type NaN"

all I am facing an issue with Arabic characters when trying to use different fonts in my project. I have attempted to encode the Arabic letters using various npm packages, but I keep receiving a TypeError: font must be of type PDFFont or n but was actuall ...

The page continues to refresh even after the fetch() method is called and the promise is resolved, despite setting e.preventDefault()

Greetings! I am currently in the process of creating a basic API using ytdl and express. Specifically, the route I am focusing on is responsible for downloading a file. app.post('/audio', (req, res) => { console.log(`Initiating audio down ...

Looking for a way to implement jQuery tabs with restrictions that only allow one tab to be active at a time while using an

In my database table, there are 4 different statuses stored in the status column - 1, 2, 3, and 4. I am looking to implement jQuery tabs or Javascript tabs with tab names as Tab A, Tab B, Tab C, and Tab D. Depending on the status retrieved from the contro ...

Display all pages in the DataTables plugin while utilizing responsive tables and additional features

I am struggling to combine the responsive and fixed header attributes of my current function with the "Show All" list feature, similar to what is demonstrated in this example: https://datatables.net/examples/advanced_init/length_menu.html I need assistanc ...

Tips on incorporating asynchronous functionality in AngularJS

I am currently utilizing AngularJS version 1.5.8 and have a specific requirement. When the user clicks on the Next button, the text inside the button should change to 'Processing...' before completing the operation. I have implemented the $q serv ...

Implementing a pull-to-refresh feature in React Native using Redux

I need to implement pull to refresh functionality, but I'm unsure of what to call from _Refresh(). My actions, constants, and reducers are stored on another page. How can I trigger the API again? Thank you in advance for your assistance. class Homewo ...

A guide to extracting functions from a `v-for` loop in a table

Beginner here. I am attempting to create a dropdown menu for the div with an id matching my specific name. For instance, let's say my table column names are: A, B, C. I only want to have a dropdown menu for column A. The template of my table looks ...

Performing a Jquery ajax post to an MVC2 action

I have a script set up to send a POST request to an endpoint, and it seems like the routing is correct as it hits the breakpoint on the server. $(document).ready(function() { var o = new Object(); o.message = 'Hi from the page'; $.ajax({ ...

Creating a Yeoman application with a personalized Node.js server

As I embark on the journey of developing a node.js and angular application using the powerful Yeoman tool, I can't help but wonder about one thing. Upon generating my application, I noticed that there are predefined tasks for grunt, such as a server ...

Struggling to implement Google OAuth in a MERN stack - facing a 400 bad request error with the package @react-oauth/google

Here is the React form and relevant code sections for the issue: import { useGoogleLogin } from '@react-oauth/google'; const SignUpForm = () => { const navigate = useNavigate(); const [name, setName] = useState(""); const [email, setEm ...