Hi Mindstickians!
I have a method with a callback inside of nodeJS where I'm trying to set a value in the outer function that can be returned with the result of the data that is being passed in the callback to a mongoose call:
'use strict';
var mongoose = require('mongoose')
,Alert = mongoose.model('Alert');
exports.getAllAlerts = function() {
var result = [];
Alert.find({}, function(err, alerts) {
if(err) {
console.log('exception while fetching alerts');
}
if(alerts) {
result = alerts;
console.log('result: ' + result);
}
});
return result;
}
How can I set the value of result[] with the value of alerts that's coming back in the mongoose callback?
Thanks in advance
AVADHESH PATEL
05-Mar-2013Hi Samual!
Most likely, find() runs asyncronously, in that case, you will always return an empty Array, because at the time you return the value, its not defined nor assigned.
You would need to rewrite your .getAllAlerts() method so it allows a callback function for itself, like
...and you would use that in a way like
YourModule.getAllAlerts(function( alerts ) {
console.log( alerts );
});