ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Mongodb Drop Collection in NodeJs

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='22' AND `tutorial_submenu`='1406' AND `tutorial_status`=1 LIMIT 1

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

bash

npm install mongodb

🧹 Step 2: Drop a Collection

js

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

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql