如何从Mongoose获取MongoClient对象?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从Mongoose获取MongoClient对象?相关的知识,希望对你有一定的参考价值。
我必须从mongoose连接对象获取MongoClient
对象,以便我可以重用Agenda
或我需要的其他地方。
db.js
// Export the mongoose instance
module.exports = () => {
mongoose.Promise = global.Promise;
try {
console.log('DBURL:', dbConfig.url);
const { url, options } = dbConfig;
mongoose
.connect(url, options)
.then(() => console.log('DB Connected'), err => console.log(err, options));
mongoose.connection.on('connected', () => {
logger.log('info', 'Mongoose default connection opened');
});
mongoose.connection.on('error', (err) => {
// logger.log('error', 'Couldn't able to connect to MongoDB', err);
// Blow system on db error
logger.log('info', 'Mongoose default connection opened');
throw err;
});
mongoose.connection.on('reconnected', () => {
logger.log('info', 'Mongo connection reconnected', arguments);
});
mongoose.connection.on('disconnecting', () => {
logger.log('error', 'Mongoose connection disconnecting', arguments);
});
mongoose.connection.on('disconnected', () => {
logger.log('error', 'Mongoose connection disconnected', arguments);
});
} catch (e) {
console.log("Couldn't connect to mongo:", e);
}
return mongoose;
};
答案
config = require('./configs');
mongoose = require('mongoose');
module.exports = function() {
var db = mongoose.connect(config.db, config.mongoDBOptions).then(
() => {
console.log('MongoDB connected')
},
(err) => {
console.log('MongoDB connection error',err)
}
);
require('../app/models/xxx.server.model');
require('../app/models/yyy.server.model');
return db;};
以上是关于如何从Mongoose获取MongoClient对象?的主要内容,如果未能解决你的问题,请参考以下文章
我怎样才能摆脱这个 MongoDB 错误? mongoose MongoNotConnectedError: MongoClient must be connected to perform this
如何使用 mongoose 从 mongoDB 中获取一定数量的对象? (Node.js)