【发布时间】:2016-08-01 08:04:47
【问题描述】:
在我正在使用的示例中是以下代码:
//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');
//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;
// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/my_database_name';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('users');
//Create some users
var user1 = {name: 'modulus admin', age: 42, roles: ['admin', 'moderator', 'user']};
var user2 = {name: 'modulus user', age: 22, roles: ['user']};
var user3 = {name: 'modulus super admin', age: 92, roles: ['super-admin', 'admin', 'moderator', 'user']};
// Insert some users
collection.insert([user1, user2, user3], function (err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
}
//Close connection
db.close();
});
}
});
如您所见,他正在connect 函数中进行操作。我想保持模块化并将连接与数据库操作分开。
我的建议是在 db 变量上创建一个单例并重用该变量。至少那是我在 Java 中会做的,我已经习惯了。
但是,我不确定,因为在示例中他没有提出类似的建议。
【问题讨论】:
-
正如你所说,你可以在说服务器启动时连接到数据库。对于以后的使用,您可以获取集合并继续
-
连接的生存时间是多少?我可以让它永远打开并仅在应用崩溃时关闭吗?