我使用的貓鼬用MongoDB的連接node.js的捕獲錯誤,現在我寫了下面的查詢當MongoDB的服務器宕機如何在運行貓鼬查詢
var trans = new transmodel({method: method, trans_id: r});
trans.save(function(err) {
if (err) {
console.error("Razor_pay_webhook Error 4 err: " + err);
res.write('statusCode: 200');
res.end();
} else {
res.write('statusCode: 400');
res.end();
}
});
我想,當我的MongoDB集羣將下降那麼當執行上面的貓鼬查詢時,我會得到'err',但是當我運行上面的查詢時,當我的mongo集羣關閉時沒有任何事發生(沒有err被調用)。任何人都可以告訴我如果我的mongodb服務器停機在我的查詢內,我該如何捕獲錯誤。另外爲了重新與我的羣集重新連接,我設置了下面的參數,但是我的節點服務器沒有嘗試再次與我的MongoDB服務器重新連接,我不知道發生了什麼問題。
var mongoose = require('mongoose');
var config = require('./config/database.js');
var DB_URL = config.db.url;
mongoose.connection.on("connected", function(ref) {
console.log("Connected to " + " DB!");
});
mongoose.connection.on("error", function(err) {
console.error('Failed to connect to DB ' + ' on startup ', err);
if (err) {
return next(err);
}
});
mongoose.connection.on('disconnected', function(err) {
console.log('Mongoose default connection to DB :' + ' disconnected');
if (err) {
return next(err);
}
});
var gracefulExit = function() {
mongoose.connection.close(function() {
console.log('Mongoose default connection with DB :' + ' is disconnected through app termination');
process.exit(0);
});
}
process.on('SIGINT', gracefulExit).on('SIGTERM', gracefulExit);
exports.con_close = function() {
console.log('Mongoose connection disconnected');
mongoose.connection.close();
}
var options = {
server: {
socketOptions: {
keepAlive: 1000,
connectTimeoutMS: 30000
}
},
replset: {
rs_name: 'replicaset',
auto_reconnect:true,
socketOptions: {
keepAlive: 1000, // doubt about it
connectTimeoutMS: 30000
}
},
user: 'root',
pass: 'G3saGT2Y',
auth: {
authdb: 'admin'
}
}
mongoose.connect(DB_URL, options, function(err) {
console.log('ho rha hai');
if (err) {
console.log('error connection to mongo server!');
console.log(err);
}
});
您的應用程序是否開始掛起 - 未響應請求? –