How can you remove all documents from a collection with Mongoose?

后端 未结 4 580
日久生厌
日久生厌 2020-12-14 05:04

I know how to...

  • Remove a single document.
  • Remove the collection itself.
  • Remove all documents from the collection with Mongo.

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 05:48

    MongoDB shell version v4.2.6
    Node v14.2.0

    Assuming you have a Tour Model: tourModel.js

    const mongoose = require('mongoose');
    
    const tourSchema = new mongoose.Schema({
      name: {
        type: String,
        required: [true, 'A tour must have a name'],
        unique: true,
        trim: true,
      },
      createdAt: {
        type: Date,
        default: Date.now(),
      },
    });
    const Tour = mongoose.model('Tour', tourSchema);
    
    module.exports = Tour;
    

    Now you want to delete all tours at once from your MongoDB, I also providing connection code to connect with the remote cluster. I used deleteMany(), if you do not pass any args to deleteMany(), then it will delete all the documents in Tour collection.

    const mongoose = require('mongoose');
    const Tour = require('./../../models/tourModel');
    const conStr = 'mongodb+srv://lord:@cluster0-eeev8.mongodb.net/tour-guide?retryWrites=true&w=majority';
    const DB = conStr.replace('','ADUSsaZEKESKZX');
    mongoose.connect(DB, {
        useNewUrlParser: true,
        useCreateIndex: true,
        useFindAndModify: false,
        useUnifiedTopology: true,
      })
      .then((con) => {
        console.log(`DB connection successful ${con.path}`);
      });
    
    const deleteAllData = async () => {
      try {
        await Tour.deleteMany();
        console.log('All Data successfully deleted');
      } catch (err) {
        console.log(err);
      }
    };
    

提交回复
热议问题