Connect Node with MongoDB
NIRBHAY MAITRA
Full-stack Developer at Mobius by Gaian with expertise in React.js, Node.js and 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.
2. Click on Connect to connect to a MongoDB deployment.
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.
6. For example, I have created the following database.
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);
}
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
This is how we will insert the data by creating Array of Objects.
And we can see our data has been inserted.
Updating Records in MongoDB
2. Records have been updated.
Delete Records from MongoDB
So this is how we perform CRUD operation in MongoDB.