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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With