如何删除Mongoose中所有集合的所有文档
How to delete all documents of all collections in Mongoose
将 Mongoose ODM 与 MongoDB 实例一起使用,如何删除数据库实例所有集合中的所有文档,而不必破坏集合本身或其索引?
对比:
await mongoose.connection.db.dropDatabase();
Deletes the given database, including all collections, documents, and indexes.
根据 Mongoose docs,这是不希望的。
遍历由 Connection.prototype.collections
hash, and use Query.prototype.deleteMany()
的值给出的数据库中的所有集合,以删除集合中的每个文档。
deleteMany()
query/operation 是异步的(它 returns 一个 Query
promise-like object). In order to iteratively perform the operations for all collections, we can map each collection to a promise with an asynchronous callback in which we await
the call, and use Promise.all
在所有查询都已解决时解决。
async function clearCollections() {
const collections = mongoose.connection.collections;
await Promise.all(Object.values(collections).map(async (collection) => {
await collection.deleteMany({}); // an empty mongodb selector object ({}) must be passed as the filter argument
}));
}
将 Mongoose ODM 与 MongoDB 实例一起使用,如何删除数据库实例所有集合中的所有文档,而不必破坏集合本身或其索引?
对比:
await mongoose.connection.db.dropDatabase();
Deletes the given database, including all collections, documents, and indexes.
根据 Mongoose docs,这是不希望的。
遍历由 Connection.prototype.collections
hash, and use Query.prototype.deleteMany()
的值给出的数据库中的所有集合,以删除集合中的每个文档。
deleteMany()
query/operation 是异步的(它 returns 一个 Query
promise-like object). In order to iteratively perform the operations for all collections, we can map each collection to a promise with an asynchronous callback in which we await
the call, and use Promise.all
在所有查询都已解决时解决。
async function clearCollections() {
const collections = mongoose.connection.collections;
await Promise.all(Object.values(collections).map(async (collection) => {
await collection.deleteMany({}); // an empty mongodb selector object ({}) must be passed as the filter argument
}));
}