Monday, 15 May 2017

javascript - Retrieving data from MongoDB using NodeJS with Express



Okay, so in the past few days I started messing with Node (because I think I should learn something that is actually useful and might get me a job). Right now, I know how to serve pages, basic routing and such. Nice. But I want to learn how to query databases for information.



Right now, I'm trying to build an app that serves as a webcomic website. So, in theory, the application should query the database when I type in the url http://localhost:3000/comic/



I have the following code in my app.js file:




router.get('/', function(req, res) {  
var name = getName();
console.log(name); // this prints "undefined"

res.render('index', {
title: name,
year: date.getFullYear()
});
});


function getName(){
db.test.find({name: "Renato"}, function(err, objs){
var returnable_name;
if (objs.length == 1)
{
returnable_name = objs[0].name;
console.log(returnable_name); // this prints "Renato", as it should
return returnable_name;
}
});

}


With this setup I get console.log(getName()) to output "undefined" in the console, but I have no idea why it doesnt get the only element that the query can actually find in the database.



I have tried searching in SO and even for examples in Google, but no success.



How the hell am I supposed to get the parameter name from the object?


Answer



NodeJs is async. You need a callback or Promise.




router.get('/', function(req, res) {
var name = '';
getName(function(data){
name = data;
console.log(name);

res.render('index', {
title: name,
year: date.getFullYear()

});
});
});

function getName(callback){
db.test.find({name: "Renato"}, function(err, objs){
var returnable_name;
if (objs.length == 1)
{
returnable_name = objs[0].name;

console.log(returnable_name); // this prints "Renato", as it should
callback(returnable_name);
}
});
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...