使用Node.js连接MongoDB的最佳方法

db2*_*791 5 mongodb node.js

我已经阅读了一些关于如何将Mongo与Node一起使用的指南,它们似乎都以不同的方式连接到数据库.一种对我有用的特殊方法是:

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

});
Run Code Online (Sandbox Code Playgroud)

然而,这对我来说似乎是低效/奇怪的,每次有app.get()新的用户或检索信息时,我都必须重新连接到数据库.

另一种似乎更适合我的方式是

var mongoose = require("mongoose")
var db = mongoose.connect("localhost:27107/users");

db.createCollection('users', function(err, collection) {});
Run Code Online (Sandbox Code Playgroud)

我已经看到有几个网站在这些方面做了些什么,但我个人无法完成上述工作.我不断收到TypeError: db.createCollection is not a function服务器端的错误.所以,我的问题是为什么上面的代码不起作用,如果第一个代码是一个很好的选择,并且有任何其他方法可以做到这一点.

kev*_*adi 11

您可以使用全局变量来保存连接(例如db),例如:

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))
    })
})
Run Code Online (Sandbox Code Playgroud)

或者,如果您愿意,还可以使用在没有回调参数的情况下调用它时返回的Promise对象MongoClient:

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))
    }))
})
Run Code Online (Sandbox Code Playgroud)

请注意,我在第二个示例中使用了ES6胖箭头函数定义.

你绝对不应该MongoClient每次都打电话.使用全局变量或Promises允许MongoDB node.js驱动程序创建一个连接池,它至少可以实现两个好处:

  • 连接在池中重用,因此在应用程序的生命周期内没有多个昂贵的设置/拆卸过程.你连接一次,让司机为你处理剩下的事情.
  • 您可以通过限制连接池的大小来控制应用程序与数据库的连接量.

编辑2018-08-24:MongoClient.connect()node.js驱动程序版本3.0及更高版本中的方法返回客户端对象而不是数据库对象.修改上面的示例以使其与最新的node.js驱动程序版本保持同步.