
Mongodb Drop Collection in NodeJs
Dropping (deleting) a collection in MongoDB using Node.js is quick and easy. Here's how to do it with both the native MongoDB driver and Mongoose.
✅ 1. Using Native MongoDB Driver
📦 Step 1: Install the MongoDB Driver
npm install mongodb
🧹 Step 2: Drop a Collection
const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/myDatabase') .then(async () => { console.log('Connected to MongoDB'); // Define model const User = mongoose.model('User', new mongoose.Schema({ name: String })); // Drop collection await User.collection.drop(); console.log('Collection dropped!'); await mongoose.disconnect(); }) .catch(err => { if (err.message.includes('ns not found')) { console.log('Collection does not exist!'); } else { console.error('Error:', err); } });
🧠 Notes
If the collection doesn’t exist, MongoDB will throw an error — handle it gracefully.
Dropping a collection deletes all documents and the structure of that collection.
Be careful: This operation is irreversible.
Let me know if you want to:
Drop all collections
Drop an entire database
Rebuild the collection afterward