Reputation: 4151
I am trying to fetch form data, query database and find number of documents that are related to that data, and console that count (for simplicity).
app.post('/process_get', function(req, res){
response = {
first_name : req.body.first_name,
last_name : req.body.last_name,
gender: req.body.gender
};
dbConn.then( function (db) {
var dbo = db.db("azima");
var count = dbo.collection('users').find({first_name: req.body.first_name}, {gender: req.body.gender}).count();
console.log(count);
});
console.log(response);
//convert the response in JSON format
res.end('Data received:\n' + JSON.stringify(req.body));
});
But I'm getting following:
Example app listening at http://:::8888
{ first_name: 'Najar Man', last_name: 'Malakar', gender: 'Male' }
Promise { <pending> }
I know this is because of asynchronous nature, but I don't know how to perform this "simple" operation, since I am new to node.js and mongodb.
How do I store the count
value to variable properly?
Upvotes: 0
Views: 501
Reputation: 2528
If you are using latest technologies. Use async/await.
app.post('/process_get',function(req, res){
response = {
first_name : req.body.first_name,
last_name : req.body.last_name,
gender: req.body.gender
};
dbConn.then( function (database) {
var dbo = database.db("azima");
var count
dbo.collection('users').find({first_name: req.body.first_name},
{gender: req.body.gender})
.count(function(err,resCount){
if(err){
console.log(err)}
else{
count = resCount
console.log(count);
res.end('Data received:\n' + JSON.stringify(req.body));
}
});
}).catch(function(e){console.log(e)})
console.log(response);
//convert the response in JSON format
});
Try to add this if okay then okay else try to share what is in catch block
More over when you will send data from mongo query then you will need to put res.send inside the dbConn.then
else it will not wait for mongodb query and you will send
Upvotes: 1