Mongodb – how to interact to second database through API on mongodb

mongodbmongodb-3.4node.js

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.

// When the mongodb server goes down, mongoose emits a 'disconnected' event
mongoose.connection.on('disconnected', () => { console.log('-> lost connection'); });
// The driver tries to automatically reconnect by default, so when the
// server starts the driver will reconnect and emit a 'reconnect' event.
mongoose.connection.on('reconnect', () => { console.log('-> reconnected'); });

// Mongoose will also emit a 'connected' event along with 'reconnect'. These
// events are interchangeable.
mongoose.connection.on('connected', () => { console.log('-> connected'); });

const MyModel = mongoose.model('Test', new mongoose.Schema({}));

// Stopping the server will emit a 'disconnected' event
await server.stop();
console.log('stopped server');

// Using callback by design, because when the driver is disconnected
// it "buffers" operations. If the 'disconnected' event was emitted, the driver
// will hold all operations until it reconnects, so "Finished query"
// won't print until **after** "restarted server" **and** "connected"
MyModel.findOne({}, function(error) {
  console.log('Finished query', error);
});

await new Promise(resolve => setTimeout(() => resolve(), 2000));

// Restarting the server will emit the 'reconnect' and 'connected' events
await server.start();
console.log('restarted server');

For your further ref here and here