programing tip

Mongoose를 사용하여 컬렉션에서 모든 문서를 제거하려면 어떻게해야합니까?

itbloger 2020. 10. 26. 07:45
반응형

Mongoose를 사용하여 컬렉션에서 모든 문서를 제거하려면 어떻게해야합니까?


방법을 알아 ...

  • 단일 문서를 제거합니다.
  • 컬렉션 자체를 제거합니다.
  • Mongo를 사용하여 컬렉션에서 모든 문서를 제거합니다.

하지만 Mongoose를 사용하여 컬렉션에서 모든 문서를 제거하는 방법을 모르겠습니다. 사용자가 버튼을 클릭 할 때 이것을하고 싶습니다. 일부 엔드 포인트에 AJAX 요청을 보내고 엔드 포인트에서 제거를 수행해야한다고 가정하지만 엔드 포인트에서 제거를 처리하는 방법을 모르겠습니다.

제 예에서는 Datetime컬렉션이 있고 사용자가 버튼을 클릭 할 때 모든 문서를 제거하려고합니다.

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) 빈 개체는 모두 일치합니다.


.remove()더 이상 사용되지 않습니다. 대신 deleteMany를 사용할 수 있습니다.

DateTime.deleteMany({}, callback).


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

참고URL : https://stackoverflow.com/questions/28139638/how-can-you-remove-all-documents-from-a-collection-with-mongoose

반응형