[英]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.