На самом деле есть более простой способ сделать это.
Я забираю код прямо из моего проекта в производстве.
Вы можете создать модуль только для обработки соединения с БД.
Я назвал его dbConection.js
/*eslint-env node*/
//Dependencies
const mongoose = require('mongoose');
//Winston Logger
const dbLog = require('./logger').get('dbCon');
//Require Models for DB
require('../models/Chat_History');
require('../models/User');
require('../models/benchmark');
//Global Variables
const MongodbPass = require('../creds/mongoKey');
//Connect to DB
const DB_Connection = mongoose.createConnection(MongodbPass.Database, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
});
//Initiate the connection
DB_Connection
.once('open', () => dbLog.info('DB Connected'))
.catch(err => dbLog.error('Error Connecting to DB' + ' ' + err));
//Load Models for Chat DB
const Chat_DB = DB_Connection.model('chat');
//Load Models for User DB
const User_DB = DB_Connection.model('user');
//Load Models for Bench DB
const Bench_DB = DB_Connection.model('bench');
//Export them all
module.exports = { Chat_DB, User_DB, Bench_DB };
Одна из примеров моделей:
//Dependencies
const mongoose = require("mongoose");
//Global Constant
const Schema = mongoose.Schema;
// Create Schema
const ChatSchema = new Schema({
channelId: {
type: String
},
chatHistory: {
type: Array,
profImg: {
type: String,
},
time: {
type: String
},
msg: {
type: String,
},
sender: {
type: String,
},
timeStamp: {
type: Date,
}
},
}, {
collection: 'Chat'
});
mongoose.model('chat', ChatSchema);
Как вы можете использовать модуль в другом файле
//Load DB models
const DB_Connection = require('../path/to/dbConnection');
const chatDB = DB_Connection.Chat_DB;
const userDB = DB_Connection.User_DB;
const benchDB = DB_Connection.Bench_DB;
//Query Different Collection on the fly.
chatDB.find({})
.then(result=>console.log(result))
.catch(err=>console.log(err));
userDB.find({})
.then(result=>console.log(result))
.catch(err=>console.log(err));
benchDB.find({})
.then(result=>console.log(result))
.catch(err=>console.log(err))