What is the best practice to send two independed MongoDB results in Express application via HTTP Method?
Here is a short example which makes it clear:
//app.js
var express = require('express');
var app = express();
var testController = require('./controllers/test');
app.get('/test', testController.getCounts);
...
Following getCounts() function wouldn't work because I can't 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});
});
};
Anyway, I would like to have those two counts in one response object.
Should I call Object2.count in the callback of Object1 even if they are not dependent to each other?
Or should I re-design it somehow else?
Thank you!
You should use Promise to achieve this task :
function getCount(obj) {
return new Promise(function (resolve, reject) {
obj.count({}, function(err,count) {
if(err) reject();
else resolve(count);
});
});
}
With Promise.all
you can trigger the two request and retrieve the results in order to add it to the response
exports.getCounts = function(req,res) {
Promise.all([getCount(Object1), getCount(Object2)])
.then(function success(result) {
res.send({'count1':result[0], 'count2':result[1]});
});
});
When you call res.send
you will end the response for the request. You could instead use res.write
, which will send a chunk to the client, and when done call res.end
;
Example:
app.get('/endpoint', function(req, res) {
res.write('Hello');
res.write('World');
res.end();
});
However, it seems like you are trying to send json back to the client which raises and problem: writing to object separately will not be valid json.
Example:
app.get('/endpoint', function(req, res) {
res.write({foo:'bar'});
res.write({hello:'world'});
res.end();
});
The response body will now be: {foo:'bar'}{hello:'world'}
which is not valid json.
There will also be a race condition between the two db queries, which means that you are not certain about the order of the data in the response.
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]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.