Open In App

How to Get a Instance of db From node-mongo native driver?

Last Updated : 27 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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_strcuture
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
Output

MongoDB Output:

output_mongodb
MongoDB Output

Next Article
Article Tags :

Similar Reads