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

后端 未结 4 579
日久生厌
日久生厌 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条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 06:04

    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:

    
    

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

提交回复
热议问题