Tips for retrieving multiple independent response data in Express js app.get callback

What is the optimal way to send two independent MongoDB results in an Express application via HTTP Method?

Check out this concise example to clarify:

//app.js
var express = require('express');
var app = express();
var testController = require('./controllers/test');
app.get('/test', testController.getCounts);
...

The getCounts() function provided will not work because it attempts to send the response twice.

///controllers/test
exports.getCounts = function(req,res) {
   Object1.count({},function(err,count){
    res.send({count:count});
   });
   Object2.count({},function(err,count){
    res.send({count:count});
   });
};

Nevertheless, I am interested in consolidating those two counts into a single response object.

Should I trigger Object2.count within the callback of Object1 even though they are unrelated?

Alternatively, should I rethink the design in some other way?

Thanks!

Answer №1

To accomplish this task, it is recommended to utilize Promises:

 function retrieveCount(data) {
    return new Promise(function (resolve, reject) {
        data.getCount({}, function(err,count) {
             if(err) reject();
             else resolve(count);
        });
    });
 }

By utilizing Promise.all, you can execute both requests and gather the outcomes in order to incorporate them into the response:

 exports.retrieveCounts = function(request,response) {
    Promise.all([retrieveCount(Data1), retrieveCount(Data2)])
    .then(function process(result) {
        response.send({'countA':result[0], 'countB':result[1]});
    });
 });

Answer №2

Once res.send is called, the response for the request will be terminated. An alternative approach is using res.write, which allows sending a chunk to the client before calling res.end to complete the response;

For instance:

app.get('/endpoint', function(req, res) {
   res.write('Hello');
   res.write('World');
   res.end();
});

However, if you are attempting to send JSON back to the client, there's an issue: writing objects separately won't result in valid JSON format.

For example:

app.get('/endpoint', function(req, res) {
   res.write({foo:'bar'});
   res.write({hello:'world'});
   res.end();
});

The response body will appear as: {foo:'bar'}{hello:'world'} which is not compliant with JSON standards.

Moreover, there exists a race condition between the two database queries, leading to uncertainty regarding the sequence of data in the response.

Here's a suggestion:

exports.getCounts = function(req,res) {
  var output = {};      

  Object1.count({},function(err,count){
     output.count1 = count;

     Object2.count({},function(err,count){
       output.count2 = count;
       res.send(output);
     });
  });
};

//Response body
{
   count1: [value],
   count2: [value]
}

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

How to Validate Response/ Data value from PHP using Ajax

Currently, I am in the process of validating a sign-up form by utilizing ajax to call a php script that checks for existing email addresses. If the email address already exists in the database, an error message should be returned to the ajax function throu ...

Search through an array, identify duplicates, and transfer them into a separate array

I am working with an array of objects containing dates and I am looking to extract objects with the same date values into a new array. Below is the code snippet. var posts = [ { "userid": 1, "rating": 4, "mood": "happy", "date": "2 ...

The error message is indicating that the function "req.assert" is not

Can you identify the issue with this code snippet (express 4.16.0, TypeError: req.assert is not a function)? userController.signupPost = function(req, res, next) { console.log(req.body); var express=require('express'); var validator = require(&a ...

Tips for organizing divs once another div has been hidden using jquery

I am working towards implementing a live result filter feature. There are three filters available: Good fit, bad fit, and scheduled. When the "Good fit" filter is clicked, it should display panels with the class "good_fit_panel". Let's assume there ar ...

Node.js and MongoDB Login Form Integration with Mongoose

I am relatively new to web development and currently working on a simple web page for user login authentication. My goal is to verify user credentials (username & password) on the LoginPage from a mongoose database, and if they are correct, redirect them t ...

Encountering an error: Reading an undefined property - NodeJS, Express, and Mongoose

These are the two functions I have: exports.list = function (req, res){ Material.find(function(err, materials) { res.render('materials/list', {title: 'Pagina Materiali', materials: materials}); }); } exports.modify = function (req ...

Solution for accessing the callee function in JavaScript slide down operation

While exploring a tutorial from CSS Tricks about animating section height, I came across a solution that I would like to implement in my Angular 2 application. Here is the function responsible for expanding sections in my app: expandSection(element) { / ...

Utilizing a nested interface in Typescript allows for creating more complex and

My current interface is structured like this: export interface Foo { data?: Foo; bar?: boolean; } Depending on the scenario, data is used as foo.data.bar or foo.bar. However, when implementing the above interface, I encounter the error message: Prope ...

Mastering the use of useMasterKey in Parse with Node.js: A guide

Greetings everyone, I have developed my app using parse.com but now I need to utilize the master key as some users have administrative roles. Initially, I attempted to use the JS SDK but was advised to switch to Cloud Code. So, I tried using Express and ...

the router is having trouble choosing the right function

When attempting to log in a user using postman with the URL http://localhost:3000/login, it seems to always trigger the register function instead. The code itself is working fine, but it's just routing to the wrong function. How can I redirect it to t ...

What steps should I take to fix the JSON code containing nested objects?

Help needed to fix JSON code with nested objects, I require assistance for correcting the json { "first_name": "John", "last_name": "Parks", "recipe_page": {"shortbread": ...

Remove a file using Mongoose and Express by simply pressing a button

Trying to delete a connected account using Express and Mongoose. When the user clicks on a button (confirming their desire to delete their account), I want their account to be removed from my user's collection. HTML code snippet: <div class=" ...

Ways to modify font color in JavaScript "type"

Recently, I came across a fascinating technique where by simply refreshing the page, the text changes sentences. I managed to implement the code successfully, however, I am having trouble changing the color, size, and alignment of the text. <script type ...

Reactive form within a parent object for nested counting

I am looking to generate a nested form based on the following data: The current data available is as follows: mainObject = { adminname: 'Saqib', adminemail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40 ...

ImageMapster for perfect alignment

I'm struggling with centering a div that contains an image using imagemapster. When I remove the JS code, the div centers perfectly fine, indicating that the issue lies with the image mapster implementation. It's a simple setup: <div class=" ...

Encountering TypeScript error TS2345 while attempting to reject a Promise with an error

I recently encountered a perplexing TypeScript error message that I am struggling to comprehend. The specific error reads as follows: error TS2345: Argument of type '(error: Error) => void | Promise' is not assignable to parameter of type & ...

What is the best way to ensure a bottom tooltip stays perfectly aligned with the right edge of its corresponding element?

Currently, I am trying to implement a tooltip above my progress bar. However, the small tooltip that I have is not functioning correctly... This is how it currently appears: https://i.sstatic.net/ZJUyT.png I need the tooltip to display above the white d ...

Enhancing Connectivity in Docker Containers for Express and Mongo with DevOps Techniques

I have been developing an exciting Express & MongoDB application purely for fun. You can check it out here: https://github.com/mwaz/oober-bck. Everything has been running smoothly offline, with different database configurations set up for various environme ...

A guide on manipulating an input field to trigger md-datepicker upon clicking

What is the best way to convert an input text into a fire md-datepicker and achieve a similar result like this? ...

Combine new data by pairing one object with a new column using MongoDB

Developing an app where quiz sets will be created with questions, options, and correct answers. Each question will appear as a form to the user without the answer. When the user selects an option and submits the form, it will go to a data set called "Answ ...