简体   繁体   English

如何使用 Mongoose 从集合中删除所有文档?

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

I know how to...我知道怎么...

  • Remove a single document.删除单个文档。
  • Remove the collection itself.删除集合本身。
  • Remove all documents from the collection with Mongo.使用 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.我假设我需要向某个端点发送 AJAX 请求并让端点执行删除操作,但我不知道如何在端点处理删除操作。

In my example, I have a Datetime collection, and I want to remove all of the documents when the user clicks a button.在我的示例中,我有一个Datetime集合,我想在用户单击按钮时删除所有文档。

api/datetime/index.js api/日期时间/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 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() is deprecated. .remove()已弃用。 instead we can use deleteMany相反,我们可以使用 deleteMany

DateTime.deleteMany({}, callback) . DateTime.deleteMany({}, callback)

In MongoDB, the db.collection.remove() method removes documents from a collection.在 MongoDB 中,db.collection.remove() 方法从集合中删除文档。 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 .来源: Mongodb

If you are using mongo sheel, just do:如果您使用的是 mongo sheel,请执行以下操作:

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:在你的客户端 js 文件中插入这个 ajax delete 方法:

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

MongoDB shell version v4.2.6 MongoDB shell 版本 v4.2.6
Node v14.2.0节点 v14.2.0

Assuming you have a Tour Model: tourModel.js假设您有一个游览模型: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.现在您想从 MongoDB 中一次删除所有游览,我还提供了连接代码以连接到远程集群。 I used deleteMany(), if you do not pass any args to deleteMany(), then it will delete all the documents in Tour collection.我使用了deleteMany(),如果你不给deleteMany()传递任何参数,那么它将删除Tour集合中的所有文档。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用猫鼬从集合中提取所有文档 - Pulling all documents from collection with mongoose 如何让猫鼬列出集合中的所有文档? 告诉集合是否为空? - How to get Mongoose to list all documents in the collection? To tell if the collection is empty? 如何在 Mongoose 中找到与给定查询值匹配的数组字段的最后一个元素的所有文档? - How can you find all documents that match the last element of an array field with a given query value in Mongoose? 猫鼬删除不会删除所有文档 - mongoose remove does not remove all documents 如何使用mongoose计算mongodb集合文档中的字段总和 - How to calculate sum of fields from mongodb collection documents using mongoose 如何从猫鼬中的另一个集合中计算文档? - How to get counting of documents from another collection in mongoose? 如何从集合中删除所有文档,而不用Javascript在Firebase中删除集合本身? - How can I delete all documents from a collection without deleting the collection itself in firebase with Javascript? 如何从猫鼬中删除模型? - How do you remove a model from mongoose? 如何将字符串推送到 mongodb 集合中的所有用户文档中? - How do you push a string into all users documents in a mongodb collection? 将一个新字段添加到集合的所有文档中,将文档字段中的值添加到 MongoDB (Mongoose) 中,记录为 300K+ - Add a new field to all documents of a collection with the value from the document field into MongoDB (Mongoose) with records of 300K+
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM