Skip to main content

Archive

Show more

Node.js Database Interaction with MongoDB

Node.js Database Interaction with MongoDB

  • Interacting with MongoDB from a Node.js application is a common task in modern web development.
  • This tutorial will cover various scenarios and methods for integrating Node.js with MongoDB for database interaction.

1. Using MongoDB Node.js Driver

The MongoDB Node.js Driver is an official MongoDB library that allows Node.js applications to interact with MongoDB databases.

Installation:

Install the MongoDB Node.js Driver using npm:

npm install mongodb

2. Connecting to MongoDB

Establishing Connection:

Connect to MongoDB using the MongoClient class:

const { MongoClient } = require('mongodb');

// Connection URI
const uri = 'mongodb://localhost:27017';

// Create a new MongoClient
const client = new MongoClient(uri);

// Connect to the MongoDB server
client.connect(err => {
  if (err) {
    console.error('Error occurred while connecting to MongoDB', err);
    return;
  }
  console.log('Connected successfully to MongoDB');
});

3. Performing CRUD Operations

Inserting Documents:

To insert a document into a MongoDB collection, use the insertOne() or insertMany() methods:

// Insert a single document
const result = await db.collection('myCollection').insertOne({ name: 'John Doe', age: 30 });

// Insert multiple documents
const result = await db.collection('myCollection').insertMany([{ name: 'Alice', age: 25 }, { name: 'Bob', age: 35 }]);

Querying Documents:

To query documents from a collection, use the find() method:

// Find all documents
const documents = await db.collection('myCollection').find().toArray();

// Find documents that match a specific criteria
const documents = await db.collection('myCollection').find({ age: { $gt: 25 } }).toArray();

Updating Documents:

To update documents in a collection, use the updateOne() or updateMany() methods:

// Update a single document
const result = await db.collection('myCollection').updateOne({ name: 'John Doe' }, { $set: { age: 40 } });

// Update multiple documents
const result = await db.collection('myCollection').updateMany({ age: { $lt: 30 } }, { $set: { status: 'Inactive' } });

Deleting Documents:

To delete documents from a collection, use the deleteOne() or deleteMany() methods:

// Delete a single document
const result = await db.collection('myCollection').deleteOne({ name: 'John Doe' });

// Delete multiple documents
const result = await db.collection('myCollection').deleteMany({ status: 'Inactive' });

4. Conclusion

Node.js provides seamless integration with MongoDB, allowing developers to build powerful and scalable applications with ease.

By mastering the interaction between Node.js and MongoDB, you can create dynamic web applications that efficiently manage data and deliver exceptional user experiences.

Comments