How to perform CRUD operations with MongoDB in Node.js



Image not found!!

Performing CRUD (Create, Read, Update, Delete) operations with MongoDB in Node.js involves using the official MongoDB Node.js driver or an ODM (Object-Document Mapper) like Mongoose. Here's a basic guide using the MongoDB driver:

1. Install MongoDB Node.js Driver

bash
npm install mongodb

2. Set up Connection

javascript
const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; // MongoDB connection string const dbName = 'your_database_name'; // Use MongoClient to connect to the server MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => { if (err) { console.error('Error connecting to MongoDB:', err); return; } console.log('Connected to MongoDB'); const db = client.db(dbName); // Perform CRUD operations here // Close the connection client.close(); });

3. Create Operation (Insert)

javascript
const collection = db.collection('your_collection_name'); // Insert one document collection.insertOne({ key: 'value' }, (err, result) => { if (err) { console.error('Error inserting document:', err); return; } console.log('Document inserted:', result.insertedId); });

4. Read Operation (Find)

javascript
// Find documents collection.find({ key: 'value' }).toArray((err, documents) => { if (err) { console.error('Error finding documents:', err); return; } console.log('Found documents:', documents); });

5. Update Operation

javascript
// Update one document collection.updateOne({ key: 'value' }, { $set: { key: 'new_value' } }, (err, result) => { if (err) { console.error('Error updating document:', err); return; } console.log('Document updated:', result.modifiedCount); });

6. Delete Operation

javascript
// Delete one document collection.deleteOne({ key: 'new_value' }, (err, result) => { if (err) { console.error('Error deleting document:', err); return; } console.log('Document deleted:', result.deletedCount); });

Replace 'your_database_name' and 'your_collection_name' with your actual database and collection names. Adjust the data and queries based on your specific use case.

Note: It's recommended to use environment variables for sensitive information like connection strings and credentials. Additionally, consider error handling and other best practices for production code.