2016-07-27 9 views
0

私はmoongoose scoket閉鎖問題に直面しています。数時間以内にサーバを起動した後、この問題が発生しています。サーバーにリクエストを送信すると、ソケットが閉じられたエラーが発生し、いつかソケットがエラーを起こしてしまいます。 MY CODE:Moongooseソケットが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

Mongoのためにキープアライブフラグのオプションを通過する呼を接続します。 TCPソケットタイマーがゼロに達すると、接続を再確立します。 var mongoOptions = {socketOptions:{keepAlive:1}}; mongoose.connect(YOUR_URI、mongoOptions); `

リンクは下記を参照:

http://mongoosejs.com/docs/connections.html
関連する問題