乐闻世界logo
搜索文章和话题

How can you remove all documents from a collection with mongoose

5 个月前提问
3 个月前修改
浏览次数91

6个答案

1
2
3
4
5
6

Mongoose 是一个 MongoDB 对象文档模型(ODM)库,它提供了一种在 Node.js 环境中优雅地处理 MongoDB 数据库的方式。在 Mongoose 中,一个集合通常通过一个模型来表示,这个模型定义了文档的结构和它们的行为。

要从 Mongoose 集合中删除所有文档,您可以使用模型的 deleteMany() 函数,无需指定过滤条件,就可以删除所有匹配的文档。下面是一个如何使用 deleteMany() 函数的示例:

javascript
// 引入 Mongoose 和连接到数据库 const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/mydatabase', {useNewUrlParser: true, useUnifiedTopology: true}); // 定义模型和模式 const Schema = mongoose.Schema; const mySchema = new Schema({ // 定义文档的结构... }); const MyModel = mongoose.model('MyCollection', mySchema); // 删除集合中的所有文档 MyModel.deleteMany({}, (err) => { if (err) { console.error('发生错误:', err); } else { console.log('成功删除集合中的所有文档。'); } });

在这个例子中,MyModel 表示连接到 MongoDB 数据库中名为 'MyCollection' 的集合。我们调用 deleteMany() 函数并传递了一个空对象 {} 作为第一个参数,这表示没有任何删除条件,即删除集合中的所有文档。回调函数提供了一个错误参数,用于处理可能发生的错误,如果删除操作成功,会执行 else 代码块。

还有另一种方式是使用 async/await 语法:

javascript
// 异步函数来删除所有文档 async function deleteAllDocuments() { try { const result = await MyModel.deleteMany({}); console.log('成功删除集合中的所有文档。', result); } catch (err) { console.error('发生错误:', err); } } // 调用异步函数 deleteAllDocuments();

在这个版本中,我们创建了一个异步函数 deleteAllDocuments,在这个函数中,我们使用 await 关键字等待 deleteMany() 操作完成。这样可以让代码更加干净和易于理解,尤其是在更复杂的逻辑中。如果操作成功,我们会记录输出结果,如果遇到错误,我们会捕获错误并记录。

请注意,在实际场景中删除所有文档是一个具有破坏性的操作,因此在生产环境中应该非常小心地使用,并确保有适当的备份和恢复计划。

2024年6月29日 12:07 回复

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

2024年6月29日 12:07 回复

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

DateTime.deleteMany({}, callback).

2024年6月29日 12:07 回复

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:

shell
db.Datetime.remove({})

In your case, you need:

You didn't show me the delete button, so this button is just an example:

shell
<a class="button__delete"></a>

Change the controller to:

shell
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:

shell
$(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!'); } }); });
2024年6月29日 12:07 回复

MongoDB shell version v4.2.6
Node v14.2.0

Assuming you have a Tour Model: tourModel.js

shell
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. I used deleteMany(), if you do not pass any args to deleteMany(), then it will delete all the documents in Tour collection.

shell
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); } };
2024年6月29日 12:07 回复

你的答案