Ren*_*ira 5 javascript mongodb node.js express
好了,在过去的几天里,我开始与节点搞乱(因为我觉得我应该学的东西,实际上是有用的,可能会得到我的工作).现在,我知道如何提供页面,基本路由等.尼斯.但我想学习如何查询数据库以获取信息.
现在,我正在尝试构建一个充当webcomic网站的应用程序.因此,理论上,当我输入url时,应用程序应该查询数据库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;
}
});
}
Run Code Online (Sandbox Code Playgroud)
通过这种设置,我可以console.log(getName())在控制台中输出"undefined",但我不知道为什么它不能获得查询在数据库中实际可以找到的唯一元素.
我试过用SO搜索,甚至用Google搜索的例子,但没有成功.
我到底该如何从对象中获取参数名称?
NodeJs 是异步的。您需要回调或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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22763 次 |
| 最近记录: |