mongo架构不使用默认的mongoose连接

时间:2017-02-14 04:49:21

标签: node.js mongodb mongoose mocha

考虑以下两个文件......

// orgSchema.js
var OrgSchema = new Schema({
   ...
});

exports.OrgDB = mongoose.model('Organization', OrgSchema);


// orgs.spec.js
var OrgDB = require('...').OrgDB;

describe('organizations', function() {
    before(function(done) {
        mongoose.Promise = Promise;
        mongoose.connect('...', done);
    });

    after(function(done) {
        mongoose.connection.close(function() {
            done();
        });
    });

    describe('simple test', function (done) {
        var org = new OrgDB();

        org.name = 'New Org';
        org.save(function(err) {
            if (err) done(err);

            done();
        });
    });
});

注意,我有两个文件。如果我将模式放在与mocha单元测试相同的相同的文件中,那么一切正常。但是,由于它(当架构位于不同的文件中),架构模型(例如mongoose.model)无法识别已经建立的默认连接,因此向我发出警告:

Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html

和错误:

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

另外,如果我将mongoose.Promise and connect行放在模式文件中,一切正常。

如何让架构使用/识别默认连接?

1 个答案:

答案 0 :(得分:1)

如果它是一个不同的文件,您需要做的就是像使用模式一样导出连接。我会做类似的事情:

const connection = mongoose.connect("mongourl")
mongoose.Promise = global.Promise
module.exports = connection

然后我会在文件中要求您使用连接。