我的应用程序中有 mongoDB。
在收听应用程序之前,我想检查 mongoDB 是否已连接。
这是最好的方法吗?
这是我的 server.js 文件:
var express = require('express');
var mongoDb = require('./mongoDb');
var app = express();
init();
function init() {
if (mongoDb.isConnected()) {
app.listen(8080, '127.0.0.1');
}
else {
console.log('error');
}
}
isConnected
运行 getDbObject
。 getDbObject
连接mongoDB并返回一个对象:connected(true/false),db(dbObject or error)。
然后, isConnected
通过连接属性解析/拒绝。
这是 mongoDb.js 文件:
//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');
// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/myDb';
var connectingDb; // promise
//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;
init();
module.exports = {
isConnected: isConnected
}
// Use connect method to connect to the Server
function init() {
connectingDb = new Promise(
function (resolve, reject) {
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
reject(err);
}
else {
console.log('Connection established to', url);
//Close connection
//db.close();
resolve(db);
}
});
}
);
}
function getDbObject() {
return connectingDb().then(myDb => {
return {
connected: true,
db: myDb
}
}
)
.catch(err => {
return {
connected: false,
db: err
}
}
)
}
function isConnected() {
return new Promise(
function(resolve, reject) {
var obj = getDbObject();
if (obj.connected == true) {
console.log('success');
resolve(true);
}
else {
console.log('error');
reject(false);
}
}
)
}
任何帮助表示赞赏!
原文由 Maria Maldini 发布,翻译遵循 CC BY-SA 4.0 许可协议
有多种方法取决于您的数据库的配置方式。对于独立(单个)实例。你可以使用这样的东西
如果您有一个包含配置服务器和多个分片的共享环境,您可以使用