我不能在2个不同的连接上使用mongoose中的2个同名模式,因为只使用了第一个的第一个模式?

时间:2012-11-14 17:34:10

标签: connection mongoose

var mongodbHost = 'mongodb://localhost:9000/';
var connectionA = require('mongoose').createConnection(mongodbHost + 'A', function(err){
    var schema = require(path.resolve(__dirname, 'migrations', 'v01_00_001', 'models', 'index')).schemas.Serial;
    debugger;
    connectionA.model('Test', schema);
    console.log('First check:', schema.statics.___XXX === connectionA.models.Test.___XXX);
}.bind(this));

var connectionB = require('mongoose').createConnection(mongodbHost + 'B', function(err){
    var schema = require(path.resolve(__dirname, 'models', 'index')).schemas.Serial;  
    debugger;
    connectionB.model('Test', schema);
    console.log('First check:', schema.statics.___XXX === connectionA.models.Test.___XXX);
    console.log('Second check:', schema.statics.___XXX === connectionB.models.Test.___XXX);
}.bind(this));
// output is true, false, false

    // While it should be: true, false, true

有人知道我会做什么吗? 问题是,当我执行第一个require('mongoose')时,我得到一个新的mongoose实例,因此其余的需求也将获得相同的实例。而mongoose在连接之间共享模式:s

任何帮助表示赞赏, 感谢

2 个答案:

答案 0 :(得分:0)

为模型指定不同的名称,但仍然对两者使用相同的集合名称:

connectionA.model('TestA', schema, 'Tests');
...
connectionB.model('TestB', schema, 'Tests');

答案 1 :(得分:0)

https://github.com/LearnBoost/mongoose/issues/1211

var mongooseA = new (require('mongoose').Mongoose)();
var mongooseB = new (require('mongoose').Mongoose)();

然后创建连接2连接...