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:

  1. Connect to MongoDB: Establish a connection to MongoDB using MongoClient.
  2. Get Database and Collection: Access the database and collection where you want to perform the delete operation.
  3. Delete One Document: Use deleteOne() to remove a single document matching the filter criteria.
  4. Delete Multiple Documents: Use deleteMany() to remove multiple documents matching the filter criteria.
  5. 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:

  1. Connect to MongoDB: Use mongoose.connect() to establish a connection to MongoDB.
  2. Define Schema and Model: Define a schema and create a model for the collection.
  3. Delete One Document: Use deleteOne() to remove a single document matching the filter criteria.
  4. Delete Multiple Documents: Use deleteMany() to remove multiple documents matching the filter criteria.
  5. Close Connection: Close the Mongoose connection after completing the operation.

Best Practices

  1. Error Handling: Implement proper error handling to manage issues during delete operations.
  2. Indexing: Index fields used in queries to improve delete performance.
  3. Testing: Test delete operations thoroughly to ensure they work as expected and do not unintentionally remove important data.
  4. Atomic Operations: MongoDB operations are atomic at the document level, which helps in maintaining data consistency.