DEV Community

phin
phin

Posted on

Connecting Node.js with MongoDB: A Step-by-Step Guide

Node.js is a popular JavaScript runtime that is widely used for building web applications. MongoDB, on the other hand, is a NoSQL document database that is known for its flexibility and scalability. In this blog post, we'll show you how to connect Node.js with MongoDB and perform basic CRUD operations using example source code.

Setting up the Development Environment

Before we can connect Node.js with MongoDB, we need to set up our development environment. First, we need to install Node.js and MongoDB on our machine. You can download Node.js from the official website (https://nodejs.org/en/) and MongoDB from the official website (https://www.mongodb.com/).

Once we have Node.js and MongoDB installed, we need to create a MongoDB instance and a database. We can do this by running the following command in the terminal:

mongod --dbpath /path/to/data/directory

This will start a MongoDB instance and create a database at the specified data directory.

Next, we need to install the necessary Node.js modules. We'll be using the mongodb module, which we can install by running the following command in the terminal:

npm install mongodb

Connecting to MongoDB from Node.js

Now that we have our development environment set up, we can start connecting Node.js with MongoDB. We'll be using the MongoClient module to establish a connection. Here's an example:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://localhost:27017/mydatabase";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

client.connect(err => {
  if (err) {
    console.error(err);
    return;
  }
  console.log("Connected successfully to server");

  // perform CRUD operations here

  client.close();
});
Enter fullscreen mode Exit fullscreen mode

In the above code, we first require the MongoClient module and define the URI of our MongoDB instance. We then create a new instance of the MongoClient class and call the connect() method to establish a connection. If there is an error, we log it to the console. If the connection is successful, we log a message to the console and perform any necessary CRUD operations.

Performing CRUD Operations with MongoDB

Now that we have a connection to MongoDB, we can perform basic CRUD (Create, Read, Update, Delete) operations using Node.js. Let's take a look at some example code:

Creating a Document:

const insertDocument = function(db, callback) {
  const collection = db.collection('users');
  collection.insertOne({ name: "John", age: 30 }, function(err, result) {
    if (err) {
      console.error(err);
      return;
    }
    console.log("Document inserted successfully");
    callback(result);
  });
}
Enter fullscreen mode Exit fullscreen mode

In the above code, we define a function that takes in a database object and a callback function. We then define a collection named 'users' and insert a new document with the name "John" and age 30. If there is an error, we log it to the console. If the insertion is successful, we log a message to the console and call the callback function with the result.

Retrieving Documents:

const findDocuments = function(db, callback) {
  const collection = db.collection('users');
  collection.find({}).toArray(function(err, documents) {
    if (err) {
      console.error(err);
      return;
    }
    console.log("Documents retrieved successfully");
    console.log(documents);
    callback(documents);
  });
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)