Sign In
Sign In

How to Connect a Node.js App to MongoDB

How to Connect a Node.js App to MongoDB
Hostman Team
Technical writer
Node.js MongoDB
21.05.2024
Reading time: 7 min

When developing Node.js applications, you might need to store data somewhere. Using application variables or files on the host machine as data storage is not always convenient. A better option to consider is connecting to an external database application.

MongoDB is great for integration with Node.js. In MongoDB, data is presented in JSON format, which works well with JavaScript. 

In this article, we'll show you how to connect a MongoDB database to your Node.js application and look at several common database queries.

This guide works for Node.js version 14 and higher and MongoDB version 4.4 and higher.

Test database

As a test database, we will use the testdb database, which contains the employees collection. It stores information about a company's employees: their department, date of birth, salary level, and other information. 

We will connect the Node.js application to this database, and we will work with the employees collection.

Creating a User in MongoDB Compass

Create a new user to work with the database. For testing purposes, we will assign the user administrator privileges for all databases; however, you shouldn't do this in production—it will negatively impact security.

Open a MongoDB Shell terminal and run the following query:

>use admin
> db.createUser({
user: "Hostman",
pwd: "password",
roles: [
{ role: "userAdmin", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" }
]
})

Output:

{ok: 1}

We have created a user named "Hostman" with a password "password" and will use it to connect to the database.

Setup

To connect a Node.js application to a MongoDB database, you need to install the additional mongodb package:

npm install mongodb --save
npm install mongodb-core --save

Connection

The main object through which we will interact with the MongoDB database is an object of the MongoClient class. Let's import this class:

const {MongoClient} = require('mongodb')

And declare the DBclient object using the constructor:

const MongoDBclient = new MongoClient('URI')

The class constructor is given a URI as input, which contains information about the user, IP, and server port. Here's the URI structure:

mongodb://login:password@IP:PORT/?authMechanism=method

In the case of a database hosted on a local machine, the URI looks like this:

mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT

Here, we are using:

  • Hostman as username;

  • password as password;

  • port 27017;

  • DEFAULT as the authorization mechanism.

Let's connect to the server with the database:

const {MongoClient} = require('mongodb')
const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT')
const connect = async() =>{
    try {
        await MongoDBclient.connect()
        console.log("Successfully connected to database")
        await MongoDBclient.close()
        console.log("Connection closed")
    } catch (e) {
        console.log(e)
    }
}
connect()

Output:

Successfully connected to database
Connection closed

Any interactions with the database are asynchronous operations, therefore, it is necessary to use async and await. Let's look at several popular operations.

Inserting documents

To insert a new document, you need to execute a query to the database with document data as an argument.

Inserting a single document

const {MongoClient} = require('mongodb')
const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT')
const employee = {
    surname: 'Smith',
    age: 45,
    salary: 260000,
    department: 'DevRel',
    date_of_birth: '15/11/1977',
    first_name: 'John'
}
const Insert = async() =>{
    try {
        await MongoDBclient.connect()
        console.log("Successfully connected to database")
        const employees = MongoDBclient.db('testdb').collection('employees')
        await employees.insertOne(employee)
        await MongoDBclient.close()
        console.log("Connection closed")
    } catch (e) {
        console.log(e)
    }
}
Insert()

Inserting multiple documents

const {MongoClient} = require('mongodb')
const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT')
const ManyEmployees = [{
    surname: 'Hernandez',
    age: 27,
    salary: 160000,
    department: 'Legal Department',
    date_of_birth: '15/05/1995',
    first_name: 'Juan'
},
    {
        surname: 'Miles',
        age: 30,
        salary: 200000,
        department: 'Tech Support',
        date_of_birth: '06/02/1992',
        first_name: 'Mary'
    }]
const Insert = async() =>{
    try {
        await MongoDBclient.connect()
        console.log("Successfully connected to database")
        const employees = MongoDBclient.db('testdb').collection('employees')
        await employees.insertMany(ManyEmployees)
        await MongoDBclient.close()
        console.log("Connection closed")
    } catch (e) {
        console.log(e)
    }
}
Insert()

Let's check the total number of documents in the collection after insertions:

const {MongoClient} = require('mongodb')
const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT')
const Count = async() =>{
    try {
        await MongoDBclient.connect()
        console.log("Successfully connected to database")
        const AllDocuments = await MongoDBclient.db('testdb').collection('employees').find().toArray()
        console.log("Number of documents in the database:", AllDocuments.length)
        await MongoDBclient.close()
        console.log("Connection closed")
    } catch (e) {
        console.log(e)
    }
}
Count()

Output:

Successfully connected to database
Number of documents in the database: 5
Connection closed

Querying documents

To query documents in the database, use the following construction:

MongoClienObject.db('dbname').collection('collectionname').operation

Where:

  • MongoClienObject is an object of the MongoClient class;

  • dbname is the name of the database we are accessing;

  • collectionname is the name of the collection we are accessing;

  • operation is the query to a database or collection, for example, findOne;

If the request is made directly to the database, then collection('collectionname') is not needed.

Let's display all documents in the employees collection:

const {MongoClient} = require('mongodb')
const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT')
const Find = async() =>{
    try {
        await MongoDBclient.connect()
        console.log("Successfully connected to database")
        const AllDocuments = await MongoDBclient.db('testdb').collection('employees').find().toArray()
        console.log(AllDocuments)
        await MongoDBclient.close()
        console.log("Connection closed")
    } catch (e) {
        console.log(e)
    }
}
Find()

Ouput:

Connection successful
[
   {
     _id: new ObjectId("637c9cbd7025c2523a76fe64"),
     surname: 'Williams',
     age: 50,
     salary: 100000,
     department: 'marketing',
     date_of_birth: '15/11/1972',
     first_name: 'Natalie'
   },
   {
     _id: new ObjectId("637ca6127025c2523a76fe65"),
     surname: 'Rubio',
     age: 35,
     salary: 200000,
     department: 'QA',
     date_of_birth: '12/06/1987',
     first_name: 'Manuel'
   }
]
Connection closed

Updating documents

Updating documents is performed in the same way as the operations above.

Updating a single document

const {MongoClient} = require('mongodb')
const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT')
const Update = async() =>{
    try {
        await MongoDBclient.connect()
        console.log("Successfully connected to database")
        const employees = MongoDBclient.db('testdb').collection('employees')
        await employees.findOneAndUpdate({first_name: 'John'} , { $set: {first_name: "Johnny"}})
        await MongoDBclient.close()
        console.log("Connection closed")
    } catch (e) {
        console.log(e)
    }
}
Update()

Updating multiple documents

const {MongoClient} = require('mongodb')
const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT')
const Update = async() =>{
    try {
        await MongoDBclient.connect()
        console.log("Successfully connected to database")
        const employees = MongoDBclient.db('testdb').collection('employees')
        await employees.updateMany({$or:[{department: 'DevRel'},{department: 'marketing'}]} , { $set: {department: "PR"}})
        await MongoDBclient.close()
        console.log("Connection closed")
    } catch (e) {
        console.log(e)
    }
}
Update()

Conclusion

MongoDB is a great tool, especially when coupled with Node.js. In this material, we used a local database, but there are other options, like cloud. At Hostman, you can deploy a MongoDB cloud database in a few seconds and start working in no time.

Node.js MongoDB
21.05.2024
Reading time: 7 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us