2016-07-27 57 views
0

我正面临猫鼬scoket cloased问题。在几个小时内启动服务器后,我得到了这个问题。如果我发送请求到服务器我得到套接字关闭错误,并在某些时候后,我得到套接字挂起错误。 我的代码:猫鼬套接字在nodejs关闭

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

对于蒙戈连接调用通过对keepalive标记的选项。当TCP套接字定时器达到零时,它将重新建立连接。 var mongoOptions = {socketOptions:{keepAlive:1}}; mongoose.connect(YOUR_URI,mongoOptions);`

见下面给出的链接: http://mongoosejs.com/docs/connections.html