使用ExpressJet,使用NodeJS从MongoDB中检索数据

好的,所以在过去的几天里,我开始搞Node了(因为我觉得我应该学习一些实际上有用的东西,并且可以帮我找份工作)。 现在,我知道如何提供页面,基本路由等。 尼斯。 但我想学习如何查询数据库的信息。

现在,我正在尝试构build一个可以作为一个webcomic网站的应用程序。 所以,理论上,当我inputurl http://localhost:3000/comic/<comicid>时,应用程序应该查询数据库。

我在我的app.js文件中有以下代码:

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

有了这个设置,我得到console.log(getName())在控制台输出“undefined”,但我不知道为什么它没有得到查询可以在数据库中实际find的唯一元素。

我试图search,甚至在谷歌的例子,但没有成功。

我该怎么从对象中获取参数名?

NodeJs是asynchronous的。 你需要一个callback或承诺 。

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

getName函数使用db.test.find对Mongo进行asynchronous调用。 您可以通过在asynchronous函数之后添加console.log来看到这一点。 喜欢这个:

 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); return returnable_name; } }); console.log('test'); // <!-- Here } 

在所有可能性中,这将输出:

 test Renato 

您需要为您的getName函数提供callback。

 router.get('/', function(req, res) { getName(function(err, name) { res.render('index', { title: name, year: date.getFullYear() }); })' }); function getName(cb){ db.test.find({name: "Renato"}, function(err, objs){ if(err) cb(err); var returnable_name; if (objs.length == 1) { returnable_name = objs[0].name; return cb(null, returnable_name); } else { // Not sure what you want to do if there are no results } }); }