2

my code below

 var mongoose = require('mongoose');
 for(let i = 0;i<600;i++)
 {

    let  db1 =  mongoose.createConnection('mongodb://127.0.0.1:27017/abc');
    db1.on('error', function(error) {
        console.log("error  = "+(i)+"  "+error +db1);
    });
    db1.on('close', function() {
        console.log("close  = "+(i)+"  "+db1);
    });
    db1.once('open', function() {
        "use strict";
        // db1.close();
    });
 }

I wanted to test mongodb ,the result is

error  = 364  MongoError: failed to connect to server [127.0.0.1:27017] on first connect[object Object]
error  = 365  MongoError: failed to connect to server [127.0.0.1:27017] on first connect[object Object]
error  = 385  MongoError: failed to connect to server [127.0.0.1:27017] on first connect[object Object].......

Another question is whether the connection needs to be closed? thanks.

morten.c
  • 3,414
  • 5
  • 40
  • 45
user2671849
  • 71
  • 1
  • 1
  • 4

1 Answers1

6

Make sure that you have Mongo running on on port 27017 of the same computer that your Node app is running. To verify that, run this in the command line:

mongo localhost:27017

You don't need to close the connection and open it multiple times. You should open the connection once in your app and close it only when you want to close your app. See those answers for more datails:

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177