使用Node.js连接到MongoDB的最佳方法 [英] Best way to connect to MongoDB using Node.js
问题描述
我已经阅读了一些有关如何将Mongo与Node结合使用的指南,它们似乎都以不同的方式连接到数据库.一种对我有效的特定方式是:
I've read a few guides on how to use Mongo with Node, and they all seem to connect to databases differently. One particular way that worked well for me was:
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) { return console.dir(err); }
db.createCollection('users', function(err, collection) {});
//Do all server/database operations in here
});
但是,对我来说,这似乎效率低下/很奇怪,每次出现app.get()
时,我都必须重新连接数据库,例如用于创建新用户或检索信息.
However, this seems inefficient/odd to me, I would have to reconnect to the database every time there is an app.get()
, like for making a new user or retrieving information.
似乎更适合我的另一种方法是
Another way that seems better suited to me is
var mongoose = require("mongoose")
var db = mongoose.connect("localhost:27107/users");
db.createCollection('users', function(err, collection) {});
我已经看到几个网站都按照这些原则进行了一些工作,但是我个人无法使上述工作正常进行.我不断收到错误TypeError: db.createCollection is not a function
服务器端.因此,我的问题是,如果第一个代码是一个不错的选择,以及是否还有其他方法可以实现上面的代码,为什么不起作用?
I've seen several sites do something along these lines, but I personally can't get the above to work. I keep getting the error TypeError: db.createCollection is not a function
server-side. So, my question is why the above code doesn't work, if the first code is a good alternative, and if there are any other ways to do this.
推荐答案
您可以使用全局变量来保持连接(例如db
),例如:
You can use a global variable to hold the connection (e.g. db
), for example:
var db = null // global variable to hold the connection
MongoClient.connect('mongodb://localhost:27017/', function(err, client) {
if(err) { console.error(err) }
db = client.db('test') // once connected, assign the connection to the global variable
})
app.get('/', function(req, res) {
db.collection('test').find({}).toArray(function(err, docs) {
if(err) { console.error(err) }
res.send(JSON.stringify(docs))
})
})
或者,如果愿意,还可以使用MongoClient
返回的 Promise对象(如果没有回调参数就调用该对象):
Or, if you prefer, you can also use the Promise object that is returned by MongoClient
if it is called without a callback argument:
var conn = MongoClient.connect('mongodb://localhost:27017/') // returns a Promise
app.get('/', function(req, res) {
conn.then(client=> client.db('test').collection('test').find({}).toArray(function(err, docs) {
if(err) { console.error(err) }
res.send(JSON.stringify(docs))
}))
})
请注意,我使用了 ES6粗箭头功能定义在第二个示例中.
Please note that I used the ES6 fat arrow function definition in the second example.
您绝对不应该每次都呼叫MongoClient
.使用全局变量或Promises允许MongoDB node.js驱动程序创建连接池,该连接池至少可以实现两个优点:
You are absolutely correct that you should not call MongoClient
every time. Using a global variable or Promises allows the MongoDB node.js driver to create a connection pool, which achieves at least two good things:
- 连接在池中被重用,因此在应用程序的生命周期内没有多个昂贵的设置/拆卸过程.您只需连接一次,然后让驾驶员为您照顾其余的一切.
- 您可以通过限制连接池的大小来控制应用程序与数据库的连接量.
编辑2018-08-24 :node.js驱动程序版本3.0及更高版本中的MongoClient.connect()
方法返回
Edit 2018-08-24: The MongoClient.connect()
method in node.js driver version 3.0 and newer returns a client object instead of a database object. The examples above were modified to keep it up to date with the latest node.js driver version.
这篇关于使用Node.js连接到MongoDB的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!