首页 > 解决方案 > mongodb 试图删除一个可能不存在的集合

问题描述

我越来越:

(node:78465) UnhandledPromiseRejectionWarning: MongoError: ns not found

我的代码:

  delete(projectId) {
    if (!this.db) return
    this.db.collection(projectId, (err, collection) => {
      // err is null here.
      collection.drop();
    });
  }

如果集合不存在,我如何确保不会收到错误消息。

标签: node.jsmongodb

解决方案


namespace因此,当尝试对不存在的集合执行某些操作时,会出现ns错误。使用您的代码,您可以执行以下操作:

 delete(projectId) {
    if (!this.db) return;
    this.db.collection(projectId).drop((err, dropOK) =>{
    if (err) {
          console.error("There is an error::", err);
          return;
        }

    if (dropOK) console.log("Collection deleted");
   });
}

理解问题的几点:

  • db.colletion(anyString)只会返回位于 anyString命名空间内的接口以及您可能希望使用该集合执行的所有操作定义。
  • 因此,只有在出现错误的情况下才会进行回调,并且只要还活着,结果就会被传递给。db.collection(anyString, (e,res)) enullresdb
  • 这就是为什么db.collection()它本身不是一个async函数并且不需要回调的原因。
  • collection.drop()就是这样的动作async去丢弃它但没有找到它,因此error.
  • 并且drop()是需要回调error识别的实际。

推荐阅读