4
const { MongoClient, ObjectID } = require('mongodb');
const debug = require('debug')('mongodb-connect');

MongoClient.connect('mongodb://localhost:27017/TodoApp', { useNewUrlParser: true }, (err, client) => {
  if (err) return debug(`Unable to connect to the server ${err}`);
  debug('Connected to the server');
  const db = client.db('TodoApp');
  db.collection('Todos').insertOne({
    text: 'Something to do',
    completed: false,
  }, (error, result) => {
    if (err) return debug(`There was a problem while inserting, ${error}`);
    debug(`Data inserted successfully ${JSON.stringify(result.ops, undefined, 2)}`);
  });
  client.close();
});

Now in the above code, I've an object of MongoClient and I called MongoClient.connect() method to connect my Node app with my local database server. In my callback I get another client object which I used to perform the database operations. I'm confused between differentiating both objects: MongoClient and client(from the callback)

2 Answers2

2

MongoClient is the name of a class that you imported from the mongodb package.

MongoClient.connect() is a static method of that class. It creates an actual instance of MongoClient (your client object) and passes it to your callback.

You cannot really do much แบith MongoClient, as it is just a representation/a class of an actual client. It is not an instance that you could call any of the methods on.

Only just by calling MongoClient.connect, you get an instance of that class that you can actually use to work with your MongoDB.

fjc
  • 5,590
  • 17
  • 36
0

It is nothing but initialized db object.

You should look into this. Mongo team has the well-documented explanation.

  1. MongoClient: Use for connecting by URL.
  2. mongoClient(client) as a parameter: Will return DB object if the connection would be successful.
Hardik Shah
  • 4,042
  • 2
  • 20
  • 41