Javascript 使用 NodeJS 和 Express 从 MongoDB 中检索数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27994972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:06:03  来源:igfitidea点击:

Retrieving data from MongoDB using NodeJS with Express

javascriptnode.jsmongodbexpress

提问by Renato Oliveira

Okay, so in the past few days I started messing with Node (because I think I should learn something that is actually useful and might get me a job). Right now, I know how to serve pages, basic routing and such. Nice. But I want to learn how to query databases for information.

好的,所以在过去的几天里,我开始使用 Node(因为我认为我应该学习一些真正有用的东西并且可能会给我一份工作)。现在,我知道如何提供页面、基本路由等。好的。但我想学习如何查询数据库的信息。

Right now, I'm trying to build an app that serves as a webcomic website. So, in theory, the application should query the database when I type in the url http://localhost:3000/comic/<comicid>

现在,我正在尝试构建一个用作网络漫画网站的应用程序。因此,理论上,当我输入 url 时,应用程序应该查询数据库http://localhost:3000/comic/<comicid>

I have the following code in my app.js file:

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

With this setup I get console.log(getName())to output "undefined" in the console, but I have no idea whyit doesnt get the only element that the query can actually find in the database.

通过此设置,我可以console.log(getName())在控制台中输出“未定义”,但我不知道为什么它没有获得查询实际上可以在数据库中找到的唯一元素。

I have tried searching in SO and even for examples in Google, but no success.

我曾尝试在 SO 中搜索,甚至在 Google 中搜索示例,但没有成功。

How the hell am I supposed to get the parameter name from the object?

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

采纳答案by MaximeF

NodeJs is async. You need a callback or Promise.

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

回答by Jordonias

The getNamefunction is making an asynchronous call to Mongo with db.test.find. You can see this by adding a console.logafter the async function. Like this:

getName函数正在对 Mongo 进行异步调用db.test.find。您可以通过console.log在 async 函数之后添加 a 来查看这一点。像这样:

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
}

In all likeliness, this will output:

很可能,这将输出:

test
Renato

You need to provide a callback to your getNamefunction.

您需要为您的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
    }
  });
}