Connect Node with MongoDB

Connect Node with MongoDB

In this Article, I’ll walk you through the basics of how to get started using MongoDB with Node.js. In today’s post, we’ll work through connecting to a MongoDB database from a Node.js script, retrieving a list of databases, and printing the results to your console.

No alt text provided for this image

  1. I have used Mongodb Compass. MongoDB Compass is?a powerful GUI for querying, aggregating, and analyzing your MongoDB data in a visual environment. Compass is free to use and source available, and can be run on macOS, Windows, and Linux. Now to create a collection, we need to create a database first

No alt text provided for this image

2. Click on Connect to connect to a MongoDB deployment.

No alt text provided for this image

3. Create a database and collection.

4. Insert data into the collection by using the following commancd

use databaseName;
db.collectionName.insertOne({name: 'xyz', age: 20, sex: 'male'})

5. In this way create 2-3 entries.

No alt text provided for this image

6. For example, I have created the following database.

No alt text provided for this image

7. Now go to VS code and connect Nodejs with MongoDB. To connect first install the npm package of mongodb:

npm i mongodb;

8. Then create mongodb.js file and type

const {MongoClient} = require('mongodb');
const url = "mongodb://localhost:27017";
const Client = new MongoClient(url)

9. Now we will create dbConnect Funtion and connect our Client. It will return promise so we have to do this with async and await. The async keyword is used to define an asynchronous function, which returns a AsyncFunction object. The await keyword is used to pause async function execution until a Promise is fulfilled, that is resolved or rejected, and to resume execution of the async function after fulfillment.

async function dbConnect(){
let result = await Client.connect();
db = result.db(databaseName);
return db.collection(collectionName);
}
No alt text provided for this image

10. Now in index.js file we will create main function and find the data, convert it into array and print to console

const main = async() => {
let data = await dbConnect();
data = await data.find().toArray();
console.log(data);
}

Now as you can see we have the data which we entered in MongoDB compass is consoled in our VS code terminal.

Inserting Data from MongoDB

No alt text provided for this image

This is how we will insert the data by creating Array of Objects.

No alt text provided for this image

And we can see our data has been inserted.

Updating Records in MongoDB

No alt text provided for this image

  1. We use updateOne() to update the records ,

No alt text provided for this image

2. Records have been updated.

Delete Records from MongoDB

No alt text provided for this image

So this is how we perform CRUD operation in MongoDB.

要查看或添加评论,请登录

NIRBHAY MAITRA的更多文章

社区洞察

其他会员也浏览了