我找不到如何在多个文件中共享mongoose连接的解决方案,这里有一个例子
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");
}
但它不起作用,我无法从集合中删除任何对象,即使查找功能也不起作用。有效的是,如果我在每个文件中明确声明这两行,
if(!mongoose.connection)
mongoose.connect('mongodb://localhost/test');
答案 0 :(得分:0)
我用以下解决方案解决了这个问题
var mongoose = require('mongoose');
if (mongoose.connection.readyState == 0) {
mongoose.connect('mongodb://localhost/test');
}
module.exports = mongoose;