# Setting up a local MongoDB connection in Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Dec 10, 2020, updated Oct 1, 2022. Topics: Node.js, Mongoose, MongoDB.
Canonical URL: https://attacomsian.com/blog/nodejs-mongodb-local-connection

> Learn how to use the MongoDB official driver for Node.js and Mongoose to connect to a local MongoDB instance.

In an [earlier article](https://attacomsian.com/blog/working-with-mongodb-using-mongo-shell), we looked at how to access and use MongoDB from the terminal by using the `mongo` shell &mdash; 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](https://attacomsian.com/blog/install-mongodb-macos) and [Ubuntu](https://attacomsian.com/blog/install-mongodb-ubuntu-18-04)) to install and configure MongoDB.

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

```bash
$ mongo --version
```

You should see a response similar to the following:

```bash
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](https://www.npmjs.com/package/mongodb) or the [Mongoose](https://attacomsian.com/blog/nodejs-getting-started-with-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:

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

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

```bash
$ npm init -y
```

### Connecting with MongoDB native driver

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

```bash
$ npm install mongodb --save
```

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

```javascript
const MongoClient = require('mongodb').MongoClient
```

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

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

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

```javascript
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:

<p class="file-desc"><span>connect-mongo-client.js</span></p>

```javascript
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:

```bash
$ 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:

```javascript
const courses = db.collection('courses')
```

#### Insert data to a collection

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

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

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

```javascript
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:

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

You should see the following output:

```bash
[
  { _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:

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
client.close()
```

#### Promises and Async-Await

MongoDB native client also supports JavaScript [promises](https://attacomsian.com/blog/promises-javascript) and [async-await](https://attacomsian.com/blog/async-await-javascript) syntax.

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

```javascript
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:

```javascript
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:

```bash
$ npm install mongoose --save
```

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

```javascript
const mongoose = require('mongoose')
```

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

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

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

<p class="file-desc"><span>connect-mongoose.js</span></p>

```javascript
;(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:

```bash
$ 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](https://github.com/attacomsian/code-examples/tree/master/nodejs/mongodb-local-connect) 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](https://attacomsian.com/blog/nodejs-getting-started-with-mongoose)). Meanwhile, you should check out the Mongoose [official documentation](https://mongoosejs.com/) to learn more about object modeling and schema definitions.
