【问题标题】:Inject unique mongoose instance in module在模块中注入唯一的猫鼬实例
【发布时间】: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


    【解决方案1】:

    所以猫鼬使用单例模式。当您执行require("mongoose") 时,每次都会获得相同的构造函数实例,如mongoose/lib/index.js (source code link here) 的底部所示。 var mongoose = module.exports = exports = new Mongoose;

    要获取唯一实例,请使用以下模式:

    var singleton = require("mongoose")
    var unique = new singleton.constructor();
    //now use "unique" just as you would "mongoose"
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 2021-09-12
    • 2016-05-03
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 2020-12-16
    相关资源
    最近更新 更多