123

I know how to...

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

But I don't know how to remove all documents from the collection with Mongoose. I want to do this when the user clicks a button. I assume that I need to send an AJAX request to some endpoint and have the endpoint do the removal, but I don't know how to handle the removal at the endpoint.

In my example, I have a Datetime collection, and I want to remove all of the documents when the user clicks a button.

api/datetime/index.js

'use strict';

var express = require('express');
var controller = require('./datetime.controller');

var router = express.Router();

router.get('/', controller.index);
router.get('/:id', controller.show);
router.post('/', controller.create);
router.put('/:id', controller.update);
router.patch('/:id', controller.update);
router.delete('/:id', controller.destroy);

module.exports = router;

api/datetime/datetime.controller.js

'use strict';

var _ = require('lodash');
var Datetime = require('./datetime.model');

// Get list of datetimes
exports.index = function(req, res) {
  Datetime.find(function (err, datetimes) {
    if(err) { return handleError(res, err); }
    return res.json(200, datetimes);
  });
};

// Get a single datetime
exports.show = function(req, res) {
  Datetime.findById(req.params.id, function (err, datetime) {
    if(err) { return handleError(res, err); }
    if(!datetime) { return res.send(404); }
    return res.json(datetime);
  });
};

// Creates a new datetime in the DB.
exports.create = function(req, res) {
  Datetime.create(req.body, function(err, datetime) {
    if(err) { return handleError(res, err); }
    return res.json(201, datetime);
  });
};

// Updates an existing datetime in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  Datetime.findById(req.params.id, function (err, datetime) {
    if (err) { return handleError(res, err); }
    if(!datetime) { return res.send(404); }
    var updated = _.merge(datetime, req.body);
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, datetime);
    });
  });
};

// Deletes a datetime from the DB.
exports.destroy = function(req, res) {
  Datetime.findById(req.params.id, function (err, datetime) {
    if(err) { return handleError(res, err); }
    if(!datetime) { return res.send(404); }
    datetime.remove(function(err) {
      if(err) { return handleError(res, err); }
      return res.send(204);
    });
  });
};

function handleError(res, err) {
  return res.send(500, err);
}
Adam Zerner
  • 17,797
  • 15
  • 90
  • 156
  • you need create a delete route with a ajax delete. show me the html code button. –  Jan 25 '15 at 18:11
  • now i can help u.. just a second, i will make the code. –  Jan 25 '15 at 18:13
  • show me the html button, please. –  Jan 25 '15 at 18:13
  • @MrBearAndBear - I haven't written the code for the button yet. The button just submits an AJAX request to the endpoint - I just need to know how to structure the endpoint. – Adam Zerner Jan 25 '15 at 18:16

5 Answers5

171

DateTime.remove({}, callback) The empty object will match all of them.

chrisbajorin
  • 5,993
  • 3
  • 21
  • 34
  • 30
    Please be aware that .remove() is being deprecated. `Use deleteOne, deleteMany or bulkWrite instead.` in mongoose https://github.com/Automattic/mongoose/issues/6880 – Pedro Luz Jan 03 '19 at 16:53
  • 1
    @PedroLuz I haven't used Mongoose in a year. I'm happy to update my answer, but I still see Model#remove in the docs of the most recent version. The discussion you've linked is saying mongo has deprecated them, but mongoose hasn't. Is there a specific release where it was added to the deprecation list (or a version in which it's expected to be removed) so that I can be explicit in my "prior to version x.y.z..."? – chrisbajorin Apr 19 '19 at 16:34
  • 4
    remove is deprecated – gazdagergo Jul 12 '19 at 12:52
  • 1
    DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead. @chrisbajorin – Anthony Mar 30 '20 at 21:40
120

.remove() is deprecated. instead we can use deleteMany

DateTime.deleteMany({}, callback).

Henok Tesfaye
  • 8,287
  • 13
  • 47
  • 84
16

In MongoDB, the db.collection.remove() method removes documents from a collection. You can remove all documents from a collection, remove all documents that match a condition, or limit the operation to remove just a single document.

Source: Mongodb.

If you are using mongo sheel, just do:

db.Datetime.remove({})

In your case, you need:

You didn't show me the delete button, so this button is just an example:

<a class="button__delete"></a>

Change the controller to:

exports.destroy = function(req, res, next) {
    Datetime.remove({}, function(err) {
            if (err) {
                console.log(err)
            } else {
                res.end('success');
            }
        }
    );
};

Insert this ajax delete method in your client js file:

        $(document).ready(function(){
            $('.button__delete').click(function() {
                var dataId = $(this).attr('data-id');

                if (confirm("are u sure?")) {
                    $.ajax({
                        type: 'DELETE',
                        url: '/',
                        success: function(response) {
                            if (response == 'error') {
                                console.log('Err!');
                            }
                            else {
                                alert('Success');
                                location.reload();
                            }
                        }
                    });
                } else {
                    alert('Canceled!');
                }
            });
        });
SebaGra
  • 2,801
  • 2
  • 33
  • 43
  • Is there a way to do this with Mongoose? My stack is Angular/Express/Node/Mongo. I'm using the [angular-fullstack](https://github.com/DaftMonk/generator-angular-fullstack#endpoint) generator. I'm not sure how to run mongo commands directly, I've always used Mongoose. – Adam Zerner Jan 25 '15 at 18:10
  • are u using express to define your routes? –  Jan 25 '15 at 18:12
  • I'm using Angular, so the button is just ``. – Adam Zerner Jan 25 '15 at 18:26
  • i am sorry, i update my answer.. i didn't realize that you want delete all the collections --'. If u update your code with my, in the end of the delete process, the page will reload. –  Jan 25 '15 at 18:32
9

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:<PASSWORD>@cluster0-eeev8.mongodb.net/tour-guide?retryWrites=true&w=majority';
const DB = conStr.replace('<PASSWORD>','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);
  }
};
Rafiq
  • 8,987
  • 4
  • 35
  • 35
3

Your_Mongoose_Model.deleteMany({}) can do the job

References:
https://mongoosejs.com/docs/api.html#query_Query-deleteMany https://www.geeksforgeeks.org/mongoose-deletemany-function/

Kritish Bhattarai
  • 1,501
  • 15
  • 20