拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如何洗掉猫鼬中所有集合的所有档案

如何洗掉猫鼬中所有集合的所有档案

白鹭 - 2022-02-14 1989 0 0

将 Mongoose ODM 与 MongoDB 实体一起使用,如何洗掉数据库实体的所有集合中的所有档案,而不必破坏集合本身或其索引?

对比:

await mongoose.connection.db.dropDatabase();

根据猫鼬档案,这是不希望的。

uj5u.com热心网友回复:

遍历由Connection.prototype.collections哈希值给出的数据库中的所有集合,并用于Query.prototype.deleteMany()洗掉集合中的每个档案。

deleteMany()查询/操作是异步的(它回传一个类似QueryPromise 的物件)。为了迭代地执行所有集合的操作,我们可以将每个集合映射到一个带有异步回呼的 Promise,我们在其中await呼叫,并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
  }));
}
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *