I am on Windows environment. I am using Mongoose and nodejs for my project. I have MongoDB Replication i.e 27017(primary), 27018(slave)and 27020 is (Arbitar). now I have One more seperate db named as secondary which is running on port 27021.
My mongodb Version is
MongoDB shell version v3.4.9
For Interaction with backend I made the API. Now my problem is I want to fetch some information from my second server only when specific API calls from Frontend. This API is made/written on Primary server i.e Under Replication server.
I create the logic by which I get the information but just after my primary server is closed and not open, and generate an error that is
MongoError: topology was destroyed and then-No connection available.
My approach was.
router.post('/test, function(req, res) {
mongoose.connection.close( function () {
console.log('Primary Server close Properly');
});
const options = {
useMongoClient: true,
autoIndex: false, // Don't build indexes
reconnectTries: 10000, // Never stop trying to reconnect
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0
};
mongoose.createConnection('mongodb://127.0.0.1:27021/secondary', options);
Message.find({}).limit(2).exec(function(error, data) {
if(error) {
console.log(error);
} else {
res.send(data);
mongoose.connection.close( function () {
console.log('Secondary Server close Properly');
});
const options = {
useMongoClient: true,
autoIndex: false, // Don't build indexes
reconnectTries: 10000, // Never stop trying to reconnect
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0
};
mongoose.connect('mongodb://127.0.0.1:27017, 127.0.0.1:27018, 127.0.0.1:27020/sfr_new?replicaSet=sfr', options);
var db = mongoose.connection;
console.log('Original Connection Open Successfully');
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
}
});
})
By this I am getting the response from second server, but my first server not start. Any help is really Appreciated.
Best Answer
As per MongoDB Blog here and MongoDB Jira Blog here It seems to mean your node server's connection to your MongoDB instance was interrupted while it was trying to write to it.
As here Mongoose and the MongoDB driver both do connection buffering, so you need to shut both buffering mechanisms off to make your database operations fail fast when mongoose is not connected. By default, mongoose will wait until you reconnect before actually executing an operation. For example, the below
findOne()
callback will execute after the 'reconnect' event is emitted.For your further ref here and here