简体   繁体   English

使用MongoDB的NodeJS-实例化“ db”变量的最佳实践

[英]NodeJS with MongoDB - best practice to instantiate “db” variable

I'm currently trying to get a grip on NodeJS / Express / MongoDB and read several tutorials about it. 我目前正在尝试掌握NodeJS / Express / MongoDB并阅读有关它的一些教程。 In this tutorial by Christopher Buecheler , consider step 5 and 6: Christopher Buecheler的本教程中 ,请考虑步骤5和6:

In app.js , the following code is added: app.js ,添加了以下代码:

// ...
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');

app.get('/userlist', routes.userlist(db));
// ...

And in routes/index.js you can find the handler which belongs to the /userlist route: routes/index.js您可以找到属于/userlist路由的处理程序:

exports.userlist = function(db) {
    return function(req, res) {
        // do stuff
    };
};

I was confused by passing the db object to every handler, since, in my opinion, it creates a lot of redundancy, because you need to pass it to every handler and wrap an additional function around it. 我对将db对象传递给每个处理程序感到困惑,因为我认为它会产生很多冗余,因为您需要将其传递给每个处理程序并在其周围包装一个附加函数。 So I tried to add the initialisation of the db object into the routes/index.js file which seems to work fine and saves a lot of lines when dealing with more urls: 因此,我尝试将db对象的初始化添加到routes/index.js文件中,该文件似乎正常工作,并且在处理更多网址时可以节省很多行:

var mongodb = require('mongodb');
var monk = require('monk');

var db = monk('localhost:27017/nodetest1');

exports.userlist = function(req, res) {
  // do stuff
};

Since I'm new to MongoDB, are there any downsides doing it this way? 既然我是MongoDB的新手,那么这样做有什么缺点吗? What advantages would it have to pass the db object to every handler instead? db对象传递给每个处理程序有什么好处?

Personally I do it like you did, I instantiate it in the place that uses it. 就个人而言,我像您一样做,我在使用它的地方实例化了它。

But I have seen other people do it like in this tutorial, passing it over every time and I think it does make sense if you need to use that db in multiple places, think if you had many different files that all need that database... now instantiating it every time, that would be redundant. 但是我看到其他人像本教程一样这样做,每次都传递它,并且我认为如果需要在多个地方使用该数据库确实有意义,请考虑是否有许多都需要该数据库的不同文件。现在每次实例化它,那将是多余的。

Well, that's my 2 cents... not sure there is any "good" answer to this... It might be a good practice to keep it in app.js in case you need it all over the place, but I don't think there is any disadvantage of doing otherwise if only used at a specific place. 好吧,这是我的2美分...不确定对此是否有任何“好的”答案...如果您需要在各处放置它,最好将它保存在app.js中,但是我不知道如果只在特定的地方使用,则认为这样做有任何不利之处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM