Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  126] [ 6]  / answers: 1 / hits: 27914  / 10 Years ago, sat, january 17, 2015, 12:00:00

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/<comicid>



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?


More From » node.js

 Answers
87

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);
}
});
}

[#68178] Wednesday, January 14, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keyonna

Total Points: 521
Total Questions: 104
Total Answers: 96

Location: Samoa
Member since Tue, May 3, 2022
2 Years ago
keyonna questions
;