跨多个模型导出和重用我的mongoose连接

JuJ*_*oDi 9 mongoose mongodb node.js

我有一个目录结构

./lib
./lib/model1.js
./lib/model2.js
Run Code Online (Sandbox Code Playgroud)

两个模型都使用mongoose连接到同一个MongoDB实例,但定义了不同的模型:

// model1.js
var mongoose = require ('mongoose');
mongoose.connect ('bla')
var db = mongoose.connection;

var schema1, model1;

db.on('error', console.error.bind(console, 'database, why you no connect?'));

db.once('open', function callback () {

  schema1 = mongoose.Schema({
    // some properties
  });

  model1 = mongoose.model1 ('model1', schema1);

});
Run Code Online (Sandbox Code Playgroud)

创建数据库连接一次并为每个模型重用它的最佳方法是什么?什么是最好的目录结构?也许./lib/middleware/db.js?

这个问题似乎很相关,但它使用mongodb npm模块而不是mongoose,问题不清楚,所有作者的评论都被删除了.

Joh*_*yHK 13

您应该只mongoose.connect在应用程序的启动代码中调用一次.这将为您的应用程序创建默认连接池.

您model1.js和model2.js文件通过调用将mongoose.model它们绑定到默认连接来创建模型.

所以它实际上是由Mongoose为您处理的.

  • 所以@JohnnyHK,我只想验证一些事情.你是说人们不必真正导出猫鼬对象,只要他们连接到他们的dbs,因为他们在简单地使用require('mongoose')语句时总是在整个代码中拥有相同的对象? (3认同)

Đức*_*yễn 9

在./app.js中:

var mongoose = require('mongoose');
mongoose.connect('connStr'); //connect once
Run Code Online (Sandbox Code Playgroud)

在./lib/model1.js中:

var mongoose = require('mongoose');
var model1 = mongoose.model('model1', {
  foo1: { type: String, required: false},
  bar1: { type: String, required: false}
});
module.exports = model1;
Run Code Online (Sandbox Code Playgroud)

在./lib/model2.js中:

var mongoose = require('mongoose');
var model2 = mongoose.model('model2', {
  foo2: { type: String, required: false},
  bar2: { type: String, required: false}
});
module.exports = model2;
Run Code Online (Sandbox Code Playgroud)

然后使用这样的模型(例如In ./routes.js):

var model1 = require('./lib/model1.js');
var m1 = new model1({
   foo: 'value_for_foo',
   bar: 'value_for_bar'
});

m1.save(function (err) {
    if (err) {console.log(err.stack);}    
    console.log('saving done...');
});
Run Code Online (Sandbox Code Playgroud)

  • 如果我有多个连接怎么办?猫鼬不再工作 (2认同)