2016-07-27 82 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