0% completed
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.
Before we can connect to MongoDB from a NodeJS application, we need to set up our development environment.
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.
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.
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.
Install the official MongoDB NodeJS driver using npm.
npm install mongodb
This will add the MongoDB driver to your project dependencies.
Create a new file named app.js
in your project directory. This file will contain the code to connect to MongoDB.
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:
Import MongoClient: Import the MongoClient
class from the MongoDB driver.
const { MongoClient } = require('mongodb');
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";
Create MongoClient: Create a new MongoClient
instance with the specified URI and options.
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
Connect to MongoDB: Connect the client to the MongoDB server using the connect
method.
await client.connect(); console.log("Connected successfully to MongoDB");
Specify Database and Collection: Specify the database and collection you want to work with.
const database = client.db('testDB'); const collection = database.collection('testCollection');
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}`);
Close the Connection: Ensure the client closes the connection when operations are complete.
await client.close();
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.
.....
.....
.....