使用 NodeJS 和 Express 从 MongoDB 检索数据

Retrieving data from MongoDB using NodeJS with Express

本文关键字:MongoDB 检索 数据 Express NodeJS 使用      更新时间:2023-09-26

好吧,所以在过去的几天里,我开始搞砸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
    }
  });
}