Learning MongoDB

0% completed

Previous
Next
Connect MongoDb with NodeJs

Connecting MongoDB with NodeJS allows developers to leverage the power of a NoSQL database in their JavaScript applications. MongoDB, a flexible, scalable database, pairs well with NodeJS, an asynchronous JavaScript runtime. This combination is popular for building modern, scalable web applications. In this lesson, we will cover how to connect MongoDB with NodeJS using the official MongoDB NodeJS driver.

Setting Up the Environment

Before we can connect to MongoDB from a NodeJS application, we need to set up our development environment.

Step 1: Install NodeJS and npm

Ensure that NodeJS and npm (Node Package Manager) are installed on your machine. You can download and install NodeJS from the official website.

node -v npm -v

These commands will display the installed versions of NodeJS and npm.

Step 2: Install MongoDB

Ensure that MongoDB is installed and running on your machine. You can download and install MongoDB from the official MongoDB website.

mongod --version

This command will display the installed version of MongoDB.

Creating a NodeJS Project

Step 1: Initialize a New Project

Create a new directory for your project and initialize it with npm.

mkdir mongodb-nodejs cd mongodb-nodejs npm init -y

This will create a package.json file in your project directory.

Step 2: Install the MongoDB NodeJS Driver

Install the official MongoDB NodeJS driver using npm.

npm install mongodb

This will add the MongoDB driver to your project dependencies.

Connecting to MongoDB

Step 1: Create a Connection File

Create a new file named app.js in your project directory. This file will contain the code to connect to MongoDB.

Step 2: Write the Connection Code

In app.js, require the MongoDB driver and use it to connect to your MongoDB server.

const { MongoClient } = require('mongodb'); // Connection URI const uri = "mongodb://localhost:27017"; // Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); async function run() { try { // Connect the client to the server await client.connect(); console.log("Connected successfully to MongoDB"); // Specify the database and collection const database = client.db('testDB'); const collection = database.collection('testCollection'); // Perform operations (example: insert a document) const doc = { name: "John Doe", age: 30, profession: "Software Developer" }; const result = await collection.insertOne(doc); console.log(`New document inserted with _id: ${result.insertedId}`); } catch (err) { console.error(err); } finally { // Ensure the client will close when you finish/error await client.close(); } } run().catch(console.dir);

Explanation:

  1. Import MongoClient: Import the MongoClient class from the MongoDB driver.

    const { MongoClient } = require('mongodb');
  2. Connection URI: Define the connection URI for MongoDB. The example uses the default MongoDB server running on localhost at port 27017.

    const uri = "mongodb://localhost:27017";
  3. Create MongoClient: Create a new MongoClient instance with the specified URI and options.

    const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
  4. Connect to MongoDB: Connect the client to the MongoDB server using the connect method.

    await client.connect(); console.log("Connected successfully to MongoDB");
  5. Specify Database and Collection: Specify the database and collection you want to work with.

    const database = client.db('testDB'); const collection = database.collection('testCollection');
  6. Perform Operations: Perform database operations such as inserting a document.

    const doc = { name: "John Doe", age: 30, profession: "Software Developer" }; const result = await collection.insertOne(doc); console.log(`New document inserted with _id: ${result.insertedId}`);
  7. Close the Connection: Ensure the client closes the connection when operations are complete.

    await client.close();

Running the Application

To run the application, execute the following command in your terminal:

node app.js

You should see the output indicating a successful connection to MongoDB and the insertion of a new document.

Connecting MongoDB with NodeJS is straightforward using the official MongoDB NodeJS driver. By setting up a NodeJS project, installing the MongoDB driver, and writing the connection code, you can interact with MongoDB from your NodeJS applications. This lesson provided a step-by-step guide to setting up the environment, creating a connection, and performing basic database operations, laying the foundation for more advanced MongoDB operations in NodeJS.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next