Node JS MongoDB Delete
Deleting documents in MongoDB with Node.js involves removing existing records based on specified criteria. This can be done using either the MongoDB native driver or Mongoose, an Object Data Modeling (ODM) library. Here’s a detailed guide on how to perform delete operations using both methods.
1. Using MongoDB Native Driver
1.1 Set Up MongoDB Connection
Ensure you have MongoDB and the MongoDB native driver installed:
npm install mongodb
Code Example:
const { MongoClient } = require('mongodb');
// MongoDB URI and database name
const uri = 'mongodb://localhost:27017';
const databaseName = 'mydatabase';
async function deleteDocuments() {
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
// Connect to the MongoDB cluster
await client.connect();
console.log('Connected to MongoDB');
// Get a reference to the database and collection
const database = client.db(databaseName);
const collection = database.collection('mycollection');
// Delete a single document
const deleteResult = await collection.deleteOne({ name: 'Alice' });
console.log('Deleted documents count (deleteOne):', deleteResult.deletedCount);
// Delete multiple documents
const deleteManyResult = await collection.deleteMany({ age: { $lt: 30 } });
console.log('Deleted documents count (deleteMany):', deleteManyResult.deletedCount);
} catch (error) {
console.error('Error:', error);
} finally {
// Close the connection
await client.close();
}
}
deleteDocuments();
Explanation:
- Connect to MongoDB: Establish a connection to MongoDB using
MongoClient
. - Get Database and Collection: Access the database and collection where you want to perform the delete operation.
- Delete One Document: Use
deleteOne()
to remove a single document matching the filter criteria. - Delete Multiple Documents: Use
deleteMany()
to remove multiple documents matching the filter criteria. - Close Connection: Close the MongoDB connection after completing the operation.
2. Using Mongoose
2.1 Set Up Mongoose
Install Mongoose if you haven’t already:
npm install mongoose
Code Example:
const mongoose = require('mongoose');
// MongoDB URI
const uri = 'mongodb://localhost:27017/mydatabase';
// Connect to MongoDB
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(error => console.error('Error connecting to MongoDB:', error));
// Define a schema and model
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String
});
const User = mongoose.model('User', userSchema);
async function deleteDocuments() {
try {
// Delete a single document
const deleteResult = await User.deleteOne({ name: 'Alice' });
console.log('Deleted documents count (deleteOne):', deleteResult.deletedCount);
// Delete multiple documents
const deleteManyResult = await User.deleteMany({ age: { $lt: 30 } });
console.log('Deleted documents count (deleteMany):', deleteManyResult.deletedCount);
} catch (error) {
console.error('Error:', error);
} finally {
// Close the connection
await mongoose.connection.close();
}
}
deleteDocuments();
Explanation:
- Connect to MongoDB: Use
mongoose.connect()
to establish a connection to MongoDB. - Define Schema and Model: Define a schema and create a model for the collection.
- Delete One Document: Use
deleteOne()
to remove a single document matching the filter criteria. - Delete Multiple Documents: Use
deleteMany()
to remove multiple documents matching the filter criteria. - Close Connection: Close the Mongoose connection after completing the operation.
Best Practices
- Error Handling: Implement proper error handling to manage issues during delete operations.
- Indexing: Index fields used in queries to improve delete performance.
- Testing: Test delete operations thoroughly to ensure they work as expected and do not unintentionally remove important data.
- Atomic Operations: MongoDB operations are atomic at the document level, which helps in maintaining data consistency.