ingo
ingo

Reputation: 856

Nodejs connect mongo

I try to move datastorage in my node app to mongo db. But I have a simple problem with mongo db.

I have a button, clicked in website, will call /datastore

app.post('/datastore', (req, res) => {

    client.connect(err => {
        var dbo = client.db("test");
        dbo.listCollections().toArray(function(err, items){
            if (err) throw err;

            console.log(items);
            if (items.length == 0)
                console.log("No collections in database")
        });

        client.close();
    });

});

It works fine for the first time I click the button. But if I click the second time the button I get errors messages:

the options [servers] is not supported the options [caseTranslate] is not supported the options [dbName] is not supported the options [credentials] is not supported /Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb/lib/utils.js:132 throw err; ^

MongoError: Topology was destroyed at initializeCursor (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb-core/lib/cursor.js:596:25) at nextFunction (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb-core/lib/cursor.js:456:12) at CommandCursor.Cursor.next (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb-core/lib/cursor.js:766:3) at CommandCursor.Cursor._next (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb/lib/cursor.js:216:36) at fetchDocs (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb/lib/operations/cursor_ops.js:217:12) at toArray (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb/lib/operations/cursor_ops.js:247:3) at executeOperation (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb/lib/utils.js:416:24) at CommandCursor.Cursor.toArray (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb/lib/cursor.js:829:10) at client.connect.err (/Users/ingofoerster/Downloads/development/testrunner/start.js:256:35) at result (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb/lib/utils.js:410:17) at executeCallback (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb/lib/utils.js:402:9) at err (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb/lib/operations/mongo_client_ops.js:286:5) at connectCallback (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb/lib/operations/mongo_client_ops.js:265:5) at topology.connect (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb/lib/operations/mongo_client_ops.js:417:5) at ReplSet.connectHandler (/Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb/lib/topologies/replset.js:343:9) at Object.onceWrapper (events.js:281:20) at ReplSet.emit (events.js:193:13) at /Users/ingofoerster/Downloads/development/testrunner/node_modules/mongodb-core/lib/topologies/replset.js:786:18 at processTicksAndRejections (internal/process/task_queues.js:79:9)

I cannot explain why this happens, because I have the client.close() in my code. Any idea why I can not call the function more than one time?

Upvotes: 0

Views: 765

Answers (1)

Amolpskamble
Amolpskamble

Reputation: 978

When you clicked the button for the first time, you are able to get the result as expected, but after getting the result you are also closing the connection by calling client.close(); , which is not letting MongoDB reconnect for the second time.

Ideally, you should reuse the existing connection instead of calling connect method for each API call.

Connection pooling example is taken from here

var express = require('express');
var mongodb = require('mongodb');
var app = express();

var MongoClient = require('mongodb').MongoClient;
var db;

// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
  if(err) throw err;

  db = database;

  // Start the application after the database connection is ready
  app.listen(3000);
  console.log("Listening on port 3000");
});

// Reuse database object in request handlers
app.get("/", function(req, res) {
  db.collection("replicaset_mongo_client_collection").find({}, function(err, docs) {
    docs.each(function(err, doc) {
      if(doc) {
        console.log(doc);
      }
      else {
        res.end();
      }
    });
  });
});

Upvotes: 1

Related Questions