繁体   English   中英

如何在多个文件mongodb中共享相同的mongoose默认连接?

[英]How to share the same mongoose default connection throughout multiple files mongodb?

我找不到如何在多个文件之间共享猫鼬连接的解决方案,这是一个示例

User.js

 var mongoose = require("../DataAccess/DbConnection");
 var userSchema = new Schema({
    email: {type: String, required: true,maxlength: 40,unique:true},
 });

var User = mongoose.model('User', tutorSchema);
module.exports = User;

DbConnection.js

var mongoose=require("mongoose");

if(process.env.NODE_ENV == 'test')
{
    if(!mongoose.connection)
        mongoose.connect('mongodb://localhost/test');
}
else
{
    if(!mongoose.connection)
        mongoose.connect('mongodb://localhost/nottest');
}
module.exports = mongoose

但这无济于事,我在测试数据库中保存了一个用户现在在我的用户测试中,我试图删除一个用户

UserTest.js

   process.env.NODE_ENV = 'test';
   var mongoose=require("../DataAccess/DbConnection");
   var User =new require('../../models/User');
   User.remove({}, function(err) {
        if (!err) {
            console.log("Successfully cleared");
        }
        else {

            console.log("error clearing tutor during test");
        }

但这是行不通的,我无法从集合中删除任何对象,即使find函数也不起作用。 起作用的是,如果我在每个文件中明确声明了这两行,

if(!mongoose.connection)
    mongoose.connect('mongodb://localhost/test');

我已通过以下解决方案解决了该问题

var mongoose = require('mongoose');

if (mongoose.connection.readyState == 0) {
        mongoose.connect('mongodb://localhost/test');

}
module.exports = mongoose;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM