每次我想使用数据库时,是否都需要打开 MongoDB 连接? [英] Is it necessary to open MongoDB connection every time I want to work with the DB?
问题描述
在我使用的示例中,代码如下:
In the example I am working with is this code:
//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
函数中执行操作.我想保持模块化并将连接与数据库操作分开.
As you may see, he is doing an operation in the connect
function. I would like to keep it modular and separate the connection from DB operations.
我的建议是在 db
变量上创建一个单例并重用那个.至少这是我在 Java 中会做的事情,我已经习惯了.
My suggestion would be to make a singleton on db
variable and reuse that one. At least that's what I would do in Java to which I am used to.
但是,我不确定,因为在示例中他没有提出类似的建议.
However, I am not sure as in the example he hasn't suggested anything like that.
推荐答案
如果您想要任何类型的可扩展性,我建议不要维护一个连接.
I would recommend against maintaining one connection if you want any kind of scalability.
连接池等有许多选项,但大多数在 Node 和 MongoDB 上花费任何时间的人最终都会在某个时候转向 Mongoose.
There are a number of options for connection pooling, etc, but most folks who spend any time at all with Node and MongoDB end up moving to Mongoose at some point.
除了添加一个不错的schema层之外,它还提供了连接抽象,这样你就可以通过调用mongoose.connect()
默认为一个共享连接,或者你可以创建多个连接或参与连接通过调用 mongoose.createConnection()
进行池化.在这两种情况下,您都无需回调即可调用它,并且猫鼬机器会将对该模块的后续调用推迟到建立连接之后,这样您的代码就不必关心了.
In addition to adding a nice schema layer, it offers connection abstraction so that you can default to a shared connection by calling mongoose.connect()
, or you can create multiple connections or participate in connection pooling by calling mongoose.createConnection()
. In both cases, you call it without a callback, and the mongoose machinery will defer subsequent calls to the module until after the connection is established, so that your code doesn't have to care.
类似于您的用例的内容可能如下所示:
Something like your use case might look like so:
// in your app.js or server.js file
var mongoose = require('mongoose');
mongoose.connect(config.db.url); // assuming you have some module that handles config variables
然后在./models/user.js
Then in ./models/user.js
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
age: Number,
roles: [String]
});
mongoose.model('User',UserSchema);
最后,让我们说一个种子函数来创建你的第一批用户:
finally, in lets say a seed function to create your initial batch of users:
const mongoose = require('mongoose'),
User = mongoose.model('User');
// create some users
var user1 = new User({name: 'modulus admin', age: 42, roles: ['admin', 'moderator', 'user']});
var user2 = new User({name: 'modulus user', age: 22, roles: ['user']});
user1.save(console.log);
user2.save(console.log);
这篇关于每次我想使用数据库时,是否都需要打开 MongoDB 连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!