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:
bashnpm install mongodb
javascriptconst 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();
});
javascriptconst 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);
});
javascript// Find documents
collection.find({ key: 'value' }).toArray((err, documents) => {
if (err) {
console.error('Error finding documents:', err);
return;
}
console.log('Found documents:', documents);
});
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);
});
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.