I've encountered an unusual issue while attempting to call a callback within another callback using mongoose in my MEAN Stack setup.
myFunction = function (cb) {
var projection = {
'_id': 0,
'var1': 1,
'var2': 1
}
var order = {
'var1': 1
}
User.find({})
.select(projection).sort(order)
.exec(function(err, docs){
if(err){
console.log(err);
cb(err,docs);
} else {
console.log(docs);
cb(err,docs);
}
});
};
When trying to execute the lines with cb(err,docs), it raises a "ReferenceError: cb is not defined"
What's particularly strange is that I have functions with even more nested callbacks where "cb" works as expected.
myFunction = function(cb){
model1.count({var1:'test'}, function (err, count) {
if(count) {
model2.findOne({dat1:'hoho'}, function (err, doc){
if (err) {
console.error(err);
cb(err,doc);
} else {
cb(err,doc);
}
});
} else {
cb({message: "No items found"}, null);
}
})
}
The above code gets called as follows...
function initial(something){
myFunction(function(err, doc) {
if (err){
console.log(err.message);
} else {
//handle doc
}
});
}