Section 25 – Lesson 347 – Complete 2020 Web Development Bootcamp

Lesson 347 – Working with the Native MongoDB Driver

The most popular way of using MongoDB with Node.js is through Mongoose.

Another way of using MongoDB with Node.js is through the native Mongo driver.

The first step in using the native Mongo driver is to go to the MongoDB Drivers page and choose the Node.js driver.

To install a mongoDB database, in terminal you cd to your project directory and type –

npm install mongodb

You then copy the code found on this page, and paste it in your app.js file. This is the code –

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Create a new MongoClient
const client = new MongoClient(url, {useUnifiedTopology: true});

// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});

The const dbName = ‘myproject’; must be amended to refer to your project’s database. In this case, we will use –

const dbName = 'fruitsDB';

You must then get your mongo server up and running. To do that, open a new tab in Hyper terminal and in that new tab type the command –

mongod

The command “mongod” will start the mongo server.

You then switch back to the first tab in Hyper and run “node app.js” in the project directory and you should get this message which confirms that you are connected to the mongo database.

Connected successfully to server

In order to add a new collection ‘fruits’ and 3 records in that collection, you put this code just before client.close(); in the app.js file –

db.collection('fruits').insertMany([{name:"Apple", score: 8, review: "Great fruit!"}, {name:"Orange", score: 6, review: "Kinda sour"}, {name:"Banana", score: 9, review: "Great Stuff!"}], function(err, r) {
      assert.equal(null, err);
      assert.equal(3, r.insertedCount);
      console.log("Inserted 3 documents into the collection");

The app.js file with the added code looks like this –

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'fruitsDB';

// Create a new MongoClient
const client = new MongoClient(url, {useUnifiedTopology: true});

// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

// Insert multiple documents
  db.collection('fruits').insertMany([{name:"Apple", score: 8, review: "Great fruit!"}, {name:"Orange", score: 6, review: "Kinda sour"}, {name:"Banana", score: 9, review: "Great Stuff!"}], function(err, r) {
      assert.equal(null, err);
      assert.equal(3, r.insertedCount);
      console.log("Inserted 3 documents into the collection");

      client.close();
    });
  });

In order to read the first two records in the fruits collection, first you insert this code inside the client.connect() method –

// collection name 
  const col = db.collection('fruits');

// Get first two documents that match the query
  col.find({}).limit(2).toArray(function(err, fruits) {
  assert.equal(null, err);
  assert.equal(2, fruits.length);
  console.log("Found the following records");
  console.log(fruits);

The app.js file with the added code now looks like this –

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'fruitsDB';

// Create a new MongoClient
const client = new MongoClient(url, {useUnifiedTopology: true});

// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

// Insert multiple documents
  db.collection('fruits').insertMany([{name:"Apple", score: 8, review: "Great fruit!"}, {name:"Orange", score: 6, review: "Kinda sour"}, {name:"Banana", score: 9, review: "Great Stuff!"}], function(err, r) {
      assert.equal(null, err);
      assert.equal(3, r.insertedCount);
      console.log("Inserted 3 documents into the collection");

      // collection name
	  const col = db.collection('fruits');

      // Get first two documents that match the query
      col.find({}).limit(2).toArray(function(err, fruits) {
      assert.equal(null, err);
      assert.equal(2, fruits.length);
   	  console.log("Found the following records");
   	  console.log(fruits);
   	  

      client.close();
 		});     
 	  });
    });