Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7791417
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T21:52:48+00:00 2026-06-01T21:52:48+00:00

I am having trouble understanding node.js. Example, MongoDB access, here’s what I’ve got (mydb.js):

  • 0

I am having trouble understanding node.js.

Example, MongoDB access, here’s what I’ve got (mydb.js):

var mongodb = require('mongodb'),
    server = new mongodb.Server('staff.mongohq.com', 10030, {
        auto_reconnect: true
    }),
    db = new mongodb.Db('mydb', server);

function authenticateAndGo(db, handle) {
    db.authenticate('username', 'password', function(err) {
        if (err) {
            console.log(err);
            return;
        }
        console.log('Database user authenticated');

        var collection = new mongodb.Collection(db, 'test');

        handle(collection);
    });
}

function query(handle) {
    db.open(function(err, db) {
        if( err ) {
            console.log(err);
            return;
        }
        console.log('Database connected');

        authenticateAndGo(db, handle);
    });
};
exports.query = query;

So, if I want to use it later, I would

var mydb = require('./mydb');
mydb.query(function(collection) {
    collection.find({}, {
        limit: 10
    }).toArray(function(err, docs) {
        console.log(docs);
    });
});

But, If I do multiple calls, like so:

var mydb = require('./mydb');
mydb.query(function(collection) {
    collection.find({}, {
        limit: 10
    }).toArray(function(err, docs) {
        console.log(docs);
    });
});
mydb.query(function(collection) {
    collection.find({}, {
        limit: 10
    }).toArray(function(err, docs) {
        console.log(docs);
    });
});

I get an exception:

Error: db object already connecting, open cannot be called multiple times

I think that there is really something fundamental that I do not understand about all this and it is probable that this question is stupid …

Anyway, all help is welcome.

Thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T21:52:50+00:00Added an answer on June 1, 2026 at 9:52 pm

    mydb.js:

    var mongodb= require('mongodb'),
      server = new mongodb.Server('staff.mongohq.com', 10030, {
        auto_reconnect: true
      }),
      db1 = new mongodb.Db('mydb', server);
    
    
    // callback: (err, db)
    function openDatabase(callback) {
      db1.open(function(err, db) {
        if (err)
          return callback(err);
    
        console.log('Database connected');
    
        return callback(null, db);
      });
    }
    
    // callback: (err, collection)
    function authenticate(db, username, password, callback) {
      db.authenticate(username, password, function(err, result) {
        if (err) {
          return callback (err);
        }
        if (result) {
          var collection = new mongodb.Collection(db, 'test');
    
          // always, ALWAYS return the error object as the first argument of a callback
          return callback(null, collection);
        } else {
          return callback (new Error('authentication failed'));
        }
      });
    }
    
    exports.openDatabase = openDatabase;
    exports.authenticate = authenticate;
    

    use.js:

    var mydb = require('./mydb');
    // open the database once
    mydb.openDatabase(function(err, db) {
      if (err) {
        console.log('ERROR CONNECTING TO DATABASE');
        console.log(err);
        process.exit(1);
      }
    
      // authenticate once after you opened the database. What's the point of 
      // authenticating on-demand (for each query)?
      mydb.authenticate(db, 'usernsame', 'password', function(err, collection) {
        if (err) {
          console.log('ERROR AUTHENTICATING');
          console.log(err);
          process.exit(1);
        }
    
        // use the returned collection as many times as you like INSIDE THE CALLBACK
        collection.find({}, {limit: 10})
        .toArray(function(err, docs) {
          console.log('\n------ 1 ------');
          console.log(docs);
        });
    
        collection.find({}, {limit: 10})
        .toArray(function(err, docs) {
          console.log('\n------ 2 ------');
          console.log(docs);
        });
      });
    });
    

    Result:

    on success:

     Database connected
     Database user authenticated
    
    ------ 1 ------
    [ { _id: 4f86889079a120bf04e48550, asd: 'asd' } ]
    
    ------ 2 ------
    [ { _id: 4f86889079a120bf04e48550, asd: 'asd' } ]
    

    on failure:

    Database connected
    { [MongoError: auth fails] name: 'MongoError', errmsg: 'auth fails', ok: 0 }
    

    [Original Answer]:

    You’re opening the db multiple times (once in each query). You should open the database just once, and use the db object in the callback for later use.

    You’re using the same variable name multiple times, and that might’ve caused some confusion.

    var mongodb = require('mongodb'),
        server = new mongodb.Server('staff.mongohq.com', 10030, {
            auto_reconnect: true
        }),
        db1 = new mongodb.Db('mydb', server);
    
    function authenticateAndGo(db, handle) {
        db.authenticate('username', 'password', function(err) {
            if (err) {
                console.log(err);
                return;
            }
            console.log('Database user authenticated');
    
            var collection = new mongodb.Collection(db, 'test');
    
            handle(collection);
        });
    }
    
    function query(handle) {
        db1.open(function(err, db2) {
            if( err ) {
                console.log(err);
                return;
            }
            console.log('Database connected');
    
            authenticateAndGo(db2, handle);
        });
    };
    exports.query = query;
    

    I’ve changed the above code a little (db1 for the original db, db2 for the opened db). As you can see, you’re opening db1 multiple times, which is not good. extract the code for opening into another method and use it ONCE and use the db2 instance for all your queries/updates/removes/…

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm having trouble understanding the second half of connecting a new node into a
I'm having trouble understanding the API to set up a l2cap (or RFCOMM) client/server
from here Im having trouble understanding they say that ado.net does not include a
I'm learning more about Scala, and I'm having a little trouble understanding the example
I'm having trouble understanding how QGraphicsItemAnimation's setScaleAt function works. Here's the code I'm using:
I'm having some trouble understanding why this code won't work. I got it from
I'm having trouble understanding character encoding in node.js. I'm transmitting data and for some
I'm having trouble understanding why java secure coding is important. For example, why is
I'm having trouble understanding the behavior of the return built-in in Bash. Here is
Im having trouble understanding class relationships after being asked to research it further, would

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.