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

mongoose delete many
mongoose remove all documents
mongoose remove vs delete
mongodb delete all documents
mongoose delete related documents
mongoose watch collection
mongoose collection name
mongoose create document

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

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

How to Delete Documents with Mongoose, Remove a single document. Remove the collection itself. Remove all documents from the collection with Mongo. To remove all documents in a collection, call the remove method with an empty query document {} . The following operation deletes all documents from the bios collection: db.bios.remove( { } ) This operation is not equivalent to the drop () method. To remove all documents from a collection, it may be more efficient to use the drop () method to

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

DateTime.deleteMany({}, callback).

Mongoose, Mongoose - Delete Many Documents with model.remove() Any guides or examples appreciated. K collection.remove is deprecated. 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.

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

Remove, How do I remove all files from a collection in MongoDB? The following methods can also delete documents from a collection: db.collection.findOneAndDelete(). findOneAndDelete() provides a sort option. The option allows for the deletion of the first document sorted by the specified order. db.collection.findAndModify(). db.collection.findAndModify() provides a sort option. The option allows for the

Quickstart Mongoose Guide that will get you up to speed in no time, is an Object Data Modeling (ODM) library for MongoDB and Node. js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB. remove() is deprecated and you can use deleteOne(), deleteMany(), or bulkWrite() instead. As of "mongoose": ">=2.7.1" you can remove the document directly with the.remove() method rather than finding the document and then removing it which seems to me more efficient and easy to maintain.

db.collection.remove() - MongoDB shell method, No records should be deleted. Please mention your node.js, mongoose and MongoDB version. Nodejs 4.7.4 MongoDB 3.4.x (Wired Tiger) Mongoose added the ability to specify the collection name under the schema, or as the third argument when declaring the model. Otherwise it will use the pluralized version given by the name you map to the model.

Data Modeling Introduction, Compiling your first model; Constructing Documents; Querying; Deleting The first argument is the singular name of the collection your model is for. a way for you to listen to all inserts and updates going through your MongoDB database. In Mongoose, a "document" generally means an instance of a model. You should not have to create an instance of the Document class without going through a model. Retrieving. When you load documents from MongoDB using model functions like findOne(), you get a Mongoose document back. const doc = await MyModel.findOne(); doc instanceof MyModel; // true doc instanceof mongoose.Model; // true doc instanceof mongoose.Document; // true Updating. Mongoose documents track changes. You can modify a

Comments
  • you need create a delete route with a ajax delete. show me the html code button.
  • now i can help u.. just a second, i will make the code.
  • show me the html button, please.
  • @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.
  • check out my answer @AdamZerner
  • Please be aware that .remove() is being deprecated. Use deleteOne, deleteMany or bulkWrite instead. in mongoose github.com/Automattic/mongoose/issues/6880
  • @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..."?
  • remove is deprecated
  • Is there a way to do this with Mongoose? My stack is Angular/Express/Node/Mongo. I'm using the angular-fullstack generator. I'm not sure how to run mongo commands directly, I've always used Mongoose.
  • are u using express to define your routes?
  • I'm using Angular, so the button is just <button ng-click="clear()">Clear</button>.
  • 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.