node.js - 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();
});
}
如果集合不存在,我如何确保不会收到错误消息。
解决方案
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))
e
null
res
db
- 这就是为什么
db.collection()
它本身不是一个async
函数并且不需要回调的原因。 collection.drop()
就是这样的动作async
去丢弃它但没有找到它,因此error
.- 并且
drop()
是需要回调来error
识别的实际。
推荐阅读
- css - ASP Net Core TagHelper 添加 CSS 类
- makefile - 在 Makefile 中事先不知道目标
- wso2 - 如何在 WSO2 IoT 服务器中启动 JMS 提供程序
- database - 为什么 OrientDB EXPORT 命令不维护集群
- service-worker - 使用 Workbox 进行动态缓存
- php - 在计算总计挂钩之前在 Woocommerce 中设置自定义计算价格
- c++ - 未找到 TCS34725 ... 检查您的连接
- batch-file - 将 .pdf 文件与 Pdftk 合并
- c++ - CMAKE 错误:TBB 变量设置为未找到
- javascript - 有没有办法将多个 Array 方法应用于 1 行中的数组?