我正面临着moongoose scoket cloased问题。在几个小时内启动服务器后,我遇到了这个问题。如果我向服务器发送请求我收到套接字关闭错误,并在一段时间后我得到套接字挂起错误。 我的代码:
var mongoose = require('mongoose')
// here i am connecting mongo db with particular api
// mongoose.connect('mongodb://localhost/vs-court-agent')
var mongoUrl = 'mongodb://localhost/db-agent'
var connectWithRetry = function() {
return mongoose.connect(mongoUrl, function(err) {
if (err) {
console.error('Failed to connect to mongo on startup - retrying in 5 sec', err);
setTimeout(connectWithRetry, 5000);
}
});
};
connectWithRetry();
setInterval(function(){
if(!mongoose.connection.readyState){
console.log("mongo trying to reconnect")
connectWithRetry()
}
},1000)
路线代码:
app.post('/agent', function(req,res){
console.log(req.body)
// var newagent = new agent(req.body)
if(req.body.agentName && req.body.agentNo && req.body.agentType && req.body.agentYear){
Agent.findOne({ agentName: req.body.agentName, agentNo: req.body.agentNo, agentType: req.body.agentType, agentYear: req.body.agentYear }, function(err, result){
if(err){
return res.json({info: "Unable to get data", error:err})
}
if(result){
// return res.json({data: result})
// _.merge(result, req.body)
result.agentDetails = req.body.agentDetails
result.save(function(error){
if(error){
return res.json({info: "Error while updating data", error: err})
}
return res.json({info: "agent updated Successfully"})
})
}else{
var newAgent = new Agent(req.body, false)
newAgent.save(function(err){
if(err){
return res.json({info: "Unable to create agent", error:err})
};
return res.json({info: 'agent Created Successfully'})
})
}
})
}else{
return res.json({info: 'agentNo,agentName,agentType,agentYear are mandatory'})
}
})
答案 0 :(得分:0)
对于mongo connect call,传递keepAlive标志的选项。当TCP套接字计时器达到零时,它将重新建立连接。 var mongoOptions = {socketOptions:{keepAlive:1}}; mongoose.connect(YOUR_URI,mongoOptions);`