Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  76] [ 4]  / answers: 1 / hits: 10537  / 11 Years ago, sun, december 1, 2013, 12:00:00

How do you access mongodb count results in nodejs so the result can be accessible to the asynchronous request? I can get the result and update the database but the asynchronous request fails to access the vars or the vars are empty and the vars appear to be updated when the next asynchronous request is made. The request must not be waiting for the query to finish and the next request is filled with the previous request's variables.



testOne.increment = function(request) {   
var MongoClient = require('mongodb').MongoClient,
format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/bbb_tracking', function(err, db) {
if (err) throw err;
collection = db.collection('bbb_tio');
collection.count({vio_domain:dom}, function(err, docs) {
if (err) throw err;
if (docs > 0) {
var vio_val = 3;
} else {
var vio_val = 0;
}
if (vio_val === 3) {
event = New_Event;
var inf = 3;
}
db.close();

console.log(docs + docs);
});
});
};


In the above, even when the vars are set in scope they are not defined asynchronously. Can I get some guidance on structuring this properly so the vars are populated in the callback. Thank you!


More From » node.js

 Answers
7

Since the count function is asynchronous, you'll need to pass a callback to the increment function so that when the count is returned from the database, the code can call the callback.



testOne.increment = function(request, callback) {   
var MongoClient = require('mongodb').MongoClient,
format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/bbb_tracking', function(err, db) {
if (err) throw err;
var collection = db.collection('bbb_tio');
// not sure where the dom value comes from ?
collection.count({vio_domain:dom}, function(err, count) {
var vio_val = 0;
if (err) throw err;
if (count > 0) {
vio_val = 3;
event = New_Event;
var inf = 3;
}
db.close();

console.log(docs count: + count);
// call the callback here (err as the first parameter, and the value as the second)
callback(null, count);
});
});
};

testOne.increment({}, function(err, count) {
// the count would be here...
});


(I don't understand what the variables you've used mean or why they're not used later, so I just did a bit of a clean-up. Variables are scoped to function blocks and hoisted to the function, so you don't need to redeclare them in each if block like you had done with vio_val).


[#49940] Saturday, November 30, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deving

Total Points: 26
Total Questions: 94
Total Answers: 103

Location: Serbia
Member since Tue, Jul 26, 2022
2 Years ago
;