How to Get a Instance of db From node-mongo native driver?
Last Updated :
27 Jun, 2024
The MongoDB native driver for Node.js provides a powerful, flexible, and straightforward interface to interact with MongoDB databases directly from Node.js applications. It allows developers to connect to MongoDB, perform CRUD operations (Create, Read, Update, Delete), and utilize MongoDB's features like aggregation, indexing, and transactions. The native driver is known for its performance and ease of use, supporting both callback-based and promise-based approaches for asynchronous operations, making it a popular choice for developers building server-side applications with Node.js.
Approach
- Use npm install mongodb to install the driver.
- Import the MongoClient (MongoDB) , set connection URL and create a MongoClient instance and use it to connect to the MongoDB server.
- Use the db method on the MongoClient instance to get a reference to the database.
- Use the collection method on instance of db to get a reference to collection.
- Now perform CRUD operation on collection.
Steps to Create Application
Step 1: Make a folder named 'mongodb-instance' and navigate to it using this command.
mkdir mongodb-instance
cd mongodb-instance
Step 2: Install required module like mongodb
npm i mongodb
Updated dependencies
"dependencies": {
"mongodb": "^6.7.0"
}
Project Structure
Project Structure Example: This example shows the fetching of instance of db From node-mongo native driver.
JavaScript
const mongoDb = require("mongodb");
async function databaseConnection(dbName, collectionName) {
const URI = "xxxx-xxxx";
try {
const client = await mongoDb.MongoClient.connect(URI);
console.log("Database connected successfully");
const db = client.db(dbName);
const collection = db.collection(collectionName);
return collection;
} catch {
console.log("Database connection failed");
}
}
async function insertingData(data, collection) {
try {
await collection.insertMany(data);
console.log("Insert Data successfully");
} catch (error) {
console.log("Insertion failed");
}
}
async function deleteData(name, collection) {
try {
await collection.deleteOne({ name: name });
console.log("Deletion successfully");
} catch (error) {
console.log("Deletion failed");
}
}
async function findData(collection) {
try {
const data = await collection.find().toArray();
console.log(data);
} catch (error) {
console.log("Not Found");
}
}
async function main() {
const collection = await databaseConnection("user", "user");
const data = [
{ name: "sandeep", age: 18 },
{ name: "nakul", age: 19 },
{ name: "mohon", age: 20 },
{ name: "jatin", age: 20 },
];
// inserting data
await insertingData(data, collection);
// delete
await deleteData("mohon", collection);
// printing
await findData(collection);
}
main();
Output:
Output MongoDB Output:
MongoDB Output
Similar Reads
Native MongoDB driver for Node.js The native MongoDB driver for Node.JS is a dependency that allows our JavaScript application to interact with the NoSQL database, either locally or on the cloud through MongoDB Atlas. We are allowed to use promises as well as callbacks that gives us greater flexibility in using ES6 features. In ord
5 min read
How to Get Data from MongoDB using Node.js? One can create a simple Node.js application that allows us to get data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. Also, we use the EJS for our front end to render the simple HTML form and a table to show the data. Prerequisi
6 min read
How to get Distinct Documents from MongoDB using Node.js ? MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. It stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. MongoDB module: This module of Node.js is used for connecting the Mongo
2 min read
How to Solve MongoDB Failing to Instantiate MongoDB is a powerful and widely used NoSQL database, but like any software, it can encounter issues during instantiation. One common problem is MongoDB failing to instantiate, which can occur due to various reasons such as incorrect configurations, insufficient system resources, or conflicts with o
4 min read
How to insert single and multiple documents in Mongodb using Node.js ? MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read