【发布时间】:2014-12-04 14:17:11
【问题描述】:
我的模块注入了一个 mongoose 实例,但现在它们都使用在最后一个 mongoose 上设置的数据库。
例如,我的主模块创建了很多模块,然后对它们调用 init。
var mongoose = require('mongoose');
//...
mongoose.connect(connString);//specific to finance
var finance = require('finance').init({db:mongoose});
在我注入 mongoose 实例之前,财务模块本身需要 mongoose,因为它在 node_modules 中,所以它拥有自己的 mongoose。现在;无论我制作了多少主要模块以及调用了多少次require,它总是会得到它第一次得到的实例。
因此,所有创建的模块都将连接到上次连接设置的任何内容。
可以使用createConnection但还是不知道怎么注入mongoose,我试过了:
var mongoose = require('mongoose');
//...
var c = mongoose.createConnection(connString);//specific to finance
mongoose.connection=c;
var finance = require('finance').init({db:mongoose});
现在我收到一个错误like Cannot overwritefinancemodel once compiled.
不知何故,很难在同一个模块中获得另一个 mongoose 实例。这很有趣,因为根据 mongoose,您应该能够为不同的模型使用不同的连接,但是既然您需要一个 mongoose 实例来定义模型,那么您如何注入它呢? Require 一遍又一遍地返回同一个实例。
尝试了以下方法,但都没有成功。
console.log('deleting mongoose cache:',require.cache.mongoose=undefined);
//or this one
console.log('deleting mongoose cache:',delete require.cache.mongoose);
所以问题是:如何在具有需要唯一数据库的模型的模块中注入 mongoose?如果 main 设置了 mongoose 实例和连接以注入模型,那么如何防止它一遍又一遍地创建相同的实例?
如果可以使用 createConnection 创建唯一的连接,那么我应该在模块中注入什么?有了这个连接,我无法创建模型,需要一个 mongoose 实例。如果每个模型都需要调用 require 来获取它,那么 mongoose 是不可注入的。
【问题讨论】:
标签: node.js dependency-injection mongoose