using db.eval() to call db.collection.find()

On my Node.js platform, I have created a JavaScript function that is executed within db.eval() on MongoDB.

Here is the original JS function:

function(data){
    var d = {
        vehicle_id:data.vehicle_id,
        timestamp:{
            $gte:data.start_time,
            $lte:data.end_time
        }
    };
    var routeStatus = [];

    db.location.find(d,function(err,result){
            db.result.insert({result});
    });
}

This function has been minified into a string 'code' to be used with db.eval():

var code = 'function(data){var d={vehicle_id:data.vehicle_id, timestamp:{$gte:data.start_time, $lte:data.end_time}}; db.location.find(d,function(err,result){return result;});}';

db.eval(code,[info],function(err,result){
    log(result);

});

The 'info' object contains all necessary fields required by the function.

My main question is how can I handle the asynchronous nature of db.location.find() in order to return its result to the callback of db.eval()?

If I simply attempt to return the result from the callback of db.location.find(), nothing is returned due to it being an async call.

Answer №1

Managed to find the solution, all thanks to @NeilLunn for providing a helpful tip that made all the difference. Using the .toArray() method did the trick!

Just a simple step:

var documents = db.location.find().toArray();

And it worked like a charm.

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

What is the process of installing an npm module from a local directory?

I recently downloaded a package from Github at the following link: list.fuzzysearch.js. After unzipping it to a folder, I proceeded to install it in my project directory using the command: npm install Path/to/LocalFolder/list.fuzzysearch.js-master -S Howe ...

CSS for creating a vertical dropdown in a Bootstrap horizontal navigation bar

I recently delved into the world of twitter bootstrap and decided to construct a website from scratch using it. I've hit a roadblock while trying to develop a horizontal navigation bar with vertical dropdowns where each <li> creates a new row (c ...

Having trouble with the active class in vue-router when the route path includes "employees/add"?

I'm currently developing a project using Vue and implementing vue-router for navigation. A peculiar behavior occurs when the route changes to /employees - only the Employees menu item is activated. However, when the route switches to /employees/add, b ...

Retrieving an array value by key from user input in HTML

<input type='number' name="productId" id="productId" value="5"> <input type="number" name="quantity[]" id="quantity"> In order to retrieve the quantity value, I utilized var values = $("input[name='quantity[]']") ...

Performing an automated check on user messages every 60 seconds using JQuery and Ajax

I am in the process of developing a website with notification features, and I am looking to implement a script that will check for new messages every 60 seconds. The goal is to pass the user id through the script to trigger an alert (currently using a ba ...

Exploring the functionality of async functions that utilize the await feature within the Karma and Jasmine JavaScript

Attempting to test an async function using Karma and Jasmine in an AngularJS v1.5.0 project. This async function, labeled as (a), contains 2 await statements: async function a(){ let var1 = await b() console.log(var1) let var2 = await c() } fu ...

Showing a div with 2 unique data attributes - such as displaying Currency and Quantity

My E-Commerce website is created using HTML, JavaScript, and PHP. On the product details page, users can add products to their cart, so I show the total cart value. I need the total amount displayed in a decimal number format (10,2). Currently, when a u ...

Create a web design where two HTML elements with full width are positioned to overlap each other,

I am facing a design challenge where I need sections to span the full width of the page, but the content is contained within an article. Additionally, there is an interactive aside that needs to float above the full-width sections. Both the article and as ...

How to set the initial speed of a jQuery fadein animation

I'm looking to optimize the loading process of this div on page load so that it displays instantly and then refreshes automatically every 10 seconds. Currently, it refreshes every 10 seconds but I would like it to load instantly as well. Is there a ...

How to convert the string ID attribute to an ObjectId in MongoDB from a POST request body

I am currently working on developing a JamStack application using Next.js with a MongoDB database integrated with the mongodb driver. As part of the project, the client is required to send a JSON POST request to the endpoint "/api/foo". // Client side fe ...

handlebars.js template to check the condition based on the last item in an array

I am currently utilizing handlebars.js as my templating engine and am interested in creating a conditional segment that will only display if it happens to be the final item within an array located in the templates configuration object. { columns: [{< ...

Struggling to accurately capture the values from checkboxes and dropdown selections to ensure the correct data is displayed. Assistance is needed in this

I am facing challenges in retrieving the accurate data for display from Mat-Select and Mat-Checkbox components. My goal is to capture the selected values from users and perform if-else statements to validate conditions, displaying the correct data view if ...

The function Promise.all typically yields an array with nested arrays

Inside my node Router, the following code snippet is implemented: router.get("/single-base/:id", (req, res) => { Base.find({ _id: req.params.id }) .then(bases => { let basefetches = []; for (let base of bases) { ...

FirebaseError encountered: Unable to update document due to absence of document. Updating document is only possible if document id is hard coded

For my latest project, I have a component that can successfully create a new user and add them to the database using the function createUserWithEmailAndPassword(auth, email, password). Now, I am working on another component that will allow users to edit t ...

AngularJS unit testing with $httpBackend is impacted by conflicts with UI-Router

Here is a controller that utilizes a submit function: $scope.submit = function(){ $http.post('/api/project', $scope.project) .success(function(data, status){ $modalInstance.dismiss(true); }) .error(function(data){ ...

Angular - Issue with setting default value in a reusable FormGroup select component

My Angular reusable select component allows for the input of formControlName. This input is then used to render the select component, and the options are passed as child components and rendered inside <ng-content>. select.component.ts import {Compon ...

How to send props from a Vue.js component tag in an HTML file

I'm facing an issue with passing props from the HTML to the JavaScript code and then down to a Vue component. Here's a snippet of my index.html file: <div id="js-group-discounts"> <div class="form-group required"> <datepick ...

Tailored Queries in MongoDB Repository

I'm currently facing an issue with my model object. Consider the following structure of a Person object: class Person { String id; String firstName; String lastName; Map<String, String> properties; } Within the properties map, ...

How can we use Cypress to check if we are at the final slide in the presentation?

I am facing a challenge with multiple slideshow files that contain varying numbers of slides. Some have 10 slides, while others have 80 slides. My goal is to test every slide by using the forward and backward arrow buttons for navigation. Currently, I am c ...

Leveraging Angular, ExpressJS, and NodeJS to enable users to download a text file by simply clicking a

My goal is to incorporate a download button that allows users to download a document from my node.js server. Behold the stylish download button: https://i.sstatic.net/s4CjS.png My tech stack includes Angular for the front-end and node.js along with exp ...