[英]Unable to retrieve data from API using Express NodeJS and MongoDB, loading
[英]Retrieving data from MongoDB using NodeJS with Express
好吧,所以在过去几天我开始搞乱Node(因为我觉得我应该学到一些实际上有用的东西,可能会让我找到一份工作)。 现在,我知道如何提供页面,基本路由等。 尼斯。 但我想学习如何查询数据库以获取信息。
现在,我正在尝试构建一个充当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;
}
});
}
通过这个设置,我得到console.log(getName())
在控制台中输出“undefined”,但我不知道为什么它不能获得查询在数据库中实际可以找到的唯一元素。
我试过用SO搜索,甚至用Google搜索的例子,但没有成功。
我到底该如何从对象中获取参数名称?
NodeJs是异步的。 你需要一个回调或承诺 。
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进行异步调用。 您可以通过在异步函数之后添加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
函数提供回调。
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
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.