mongojs implementation of non blocking query
Problem
I know this must be a really silly question, but I can't figure out how to make it work. I'm learning node.js and mongojs, and this is my problem:
This is my server.js
server.get("/", function(request, response) {
if (user.whatever()) {
return response.send('true');
} else {
return response.send('false');
}
});
and this my user.js
exports.whatever = function(request, response) {
return db.tableName.findOne({
fieldName: null
}, function(error, record) {
if (record === null) {
return false;
} else {
return true;
}
});
};
the function returns "undefined". I imagine that this is a problem of blocking code, but have no idea on how to convert it. Please help!
Problem courtesy of: Sovos
Solution
You should do that as following :
server.js
server.get("/",user.whatever, function(request, response) {
if (request.user)
response.send('true');
else
response.send('false');
});
user.js
exports.whatever = function(request, response, next) {
db.tableName.findOne({ fieldName: null }, function(error, record) {
if (record === null) request.user = false;
else request.user = true;
next();
});
};
Solution courtesy of: Tolga Akyüz
Discussion
View additional discussion.