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

Adam Zerner picture Adam Zerner · Jan 25, 2015 · Viewed 108.4k times · Source

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);
}

Answer

chrisbajorin picture chrisbajorin · Jan 25, 2015

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