In an earlier article, we looked at how to access and use MongoDB from the terminal by using the mongo shell — an interactive JavaScript interface. Today, I'll share how to interact programmatically with a MongoDB local instance using Node.js.

Installing MongoDB

You must install MongoDB on your computer before you can connect to it. Follow these instructions (Mac and Ubuntu) to install and configure MongoDB.

Once the installation is completed, type the following command in your terminal:

$ mongo --version

You should see a response similar to the following:

MongoDB shell version v4.4.1
Build Info: {
    "version": "4.4.1",
    "gitVersion": "ad91a93a5a31e175f5cbf8c69561e788bbc55ce1",
    "modules": [],
    "allocator": "system",
    "environment": {
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}

Connecting with MongoDB

To connect to MongoDB in Node.js, you can either use the MongoDB official driver or the Mongoose.

I prefer to use Mongoose over the MongoDB native Node.js driver because of its simplicity and object modeling.

Let us create a new folder and switch to it:

$ mkdir mongodb-local-connect && cd mongodb-local-connect

Run the following command to create a new Node.js project:

$ npm init -y

Connecting with MongoDB native driver

You need to install the MongoDB native Node.js driver by typing the following command:

$ npm install mongodb --save

Now you can require the mongodb package and get the MongoClient object from it:

const MongoClient = require('mongodb').MongoClient

For a MongoDB instance running on the local machine, you need to use the following connection URL:

const url = 'mongodb://127.0.0.1:27017'

Next, use the connect() method of the MongoClient to connect to the MongoDB local instance:

MongoClient.connect(
  url,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true
  },
  (err, client) => {
    if (err) {
      return console.log(err)
    }

    // Specify the database you want to access
    const db = client.db('school')

    console.log(`MongoDB Connected: ${url}`)
  }
)

Notice the client.db() method. This method is used to select a MongoDB database.

Here is the complete example code:

connect-mongo-client.js

const MongoClient = require('mongodb').MongoClient

// Connect URL
const url = 'mongodb://127.0.0.1:27017'

// Connect to MongoDB
MongoClient.connect(
  url,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true
  },
  (err, client) => {
    if (err) {
      return console.log(err)
    }

    // Specify the database you want to access
    const db = client.db('school')

    console.log(`MongoDB Connected: ${url}`)
  }
)

To execute the above code, type the following command:

$ node connect-mongo-client.js
MongoDB Connected: mongodb://127.0.0.1:27017

Create and get a collection

You use the db.collection() method to get a MongoDB collection. If it doesn't already exist, it is automatically created:

const courses = db.collection('courses')

Insert data to a collection

To insert a document into an existing collection, you use the insertOne() method:

courses.insertOne({ name: 'Web Security' }, (err, result) => {})

To insert multiple documents at once, you use the insertMany() method:

courses.insertMany([
  { name: 'Web Design' }, 
  { name: 'Distributed Database' }, 
  { name: 'Artificial Intelligence' }
], (err, results) => {})

Find all documents

You can use the find() method to retrieve all documents stored in a collection:

courses.find().toArray((err, results) => {
  console.log(results)
})

You should see the following output:

[
  { _id: 5fd1c93baac6b5dd7a82b137, name: 'Web Security' },
  { _id: 5fd1c93baac6b5dd7a82b138, name: 'Web Design' },
  { _id: 5fd1c93baac6b5dd7a82b139, name: 'Distributed Database' },
  { _id: 5fd1c93baac6b5dd7a82b13a, name: 'Artificial Intelligence' }
]

Find a document

To find a specific document in the collection, you can pass an object as a parameter to the find() method:

courses.find({ name: 'Web Design' }).toArray((err, result) => {
  console.log(result)
})

// [ { _id: 5fd1c93baac6b5dd7a82b138, name: 'Web Design' } ]

Alternatively, you could also use the findOne() method to retrieve the top most document that matches the filter criteria:

courses.findOne({ name: 'Web Design' }, (err, result) => {
  console.log(result)
})

// { _id: 5fd1c93baac6b5dd7a82b138, name: 'Web Design' }

Update an existing document

To update an existing document, use the updateOne() method:

courses.updateOne(
  { name: 'Web Design' }, 
  { $set: { name: 'Web Analytics' } }, 
  (err, result) => {
    console.log(result)
})

Delete a document

To delete an existing document, you can use the deleteOne() method:

courses.deleteOne({ name: 'Distributed Database' }, (err, result) => {
  console.log(result)
})

Closing the connection

After you are done with all things, just use the close() method on the client object to close the connection:

client.close()

Promises and Async-Await

MongoDB native client also supports JavaScript promises and async-await syntax.

For example, you can replace the above findOne() method with the following example:

courses
  .findOne({ name: 'Web Design' })
  .then(result => {
    console.log(result)
  })
  .catch(err => {
    console.log(err)
  })

The following example demonstrates how you can use the async-await syntax with the MongoDB native driver:

const find = async () => {
  try {
    return await courses.findOne({ name: 'Web Design' })
  } catch (err) {
    console.log(err)
  }
}

find()

Connecting with Mongoose

To connect MongoDB with Mongoose, you need to install it with the following command:

$ npm install mongoose --save

Now you can require it in your Node.js project like the following:

const mongoose = require('mongoose')

For Mongoose, you need to include the database name in the connection URL like below:

const url = 'mongodb://127.0.0.1:27017/school'

Next, use the connect() method to connect to MongoDB:

connect-mongoose.js

;(async () => {
  try {
    await mongoose.connect(url, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useFindAndModify: false,
      useCreateIndex: true
    })
    console.log(`MongoDB Connected: ${url}`)
  } catch (err) {
    console.error(err)
  }
})()

Now you can execute the above code with the following command:

$ node connect-mongoose.js
MongoDB Connected: mongodb://127.0.0.1:27017/school

Source Code: Download the source code of this demo project from GitHub released under the MIT license.

What's next?

That's all folks for now. I wanted to write this article on MongoDB's official driver only but later decided to add Mongoose for comparison.

I'll write another article on Mongoose object modeling and data manipulation in the future (available now). Meanwhile, you should check out the Mongoose official documentation to learn more about object modeling and schema definitions.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.