使用 NodeJS 和 Express 从 MongoDB 检索数据
Retrieving data from MongoDB using NodeJS with Express
好吧,所以在过去的几天里,我开始搞砸Node(因为我认为我应该学习一些真正有用的东西,可能会给我找到工作)。现在,我知道如何提供页面,基本路由等。好。但我想学习如何查询数据库以获取信息。
现在,我正在尝试构建一个用作网络漫画网站的应用程序。因此,从理论上讲,当我键入 url 时,应用程序应该查询数据库http://localhost:3000/comic/<comicid>
我的应用程序.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
}
});
}
相关文章:
- 检索MongoDB binData并显示为<img>src
- 如何在MongoDB中检索子文档引用
- MongoDB 2.0.0 驱动程序,按 ID 检索记录时出现问题
- 使用 NodeJS 和 Express 从 MongoDB 检索数据
- 使用 Paper.js、Meteor 和 MongoDB 存储和检索路径
- 如何通过按数组字段选择来检索MongoDB文档
- 从数组中检索值,并使用MongoDB将其存储在csv文件中
- Docker日志从MongoDB中检索
- 使用node.js将数据显示在从mongodb检索到的网页上
- MongoDB和Mongoose:如何检索嵌套对象
- 从MongoDB(猫鼬)检索/发布图像
- 检索回调函数范围外的MongoDB结果
- 检索只是一个元素从Mongodb
- 我想检索值插入特定日期使用mongodb的_id
- Meteor.js + MongoDB::从深度嵌套的数组中检索值
- 流星和ReactJS -从MongoDB检索到字符串的日期
- Nodejs在从mongodb检索数据之前发送空响应
- 从mongodb检索数据并使用Google图表将其可视化
- 通过表单输入和pug模板渲染器从Mongodb检索数据
- I'm不能从mongodb检索值,即使它存在