javascript - 处理 MongoDB 查询结果中不存在的子文档的最佳方法
问题描述
我知道以前曾以某种形式或形式提出过这个问题,但我正在寻找处理查询结果的最佳方法,而无需大量 if 语句。
假设我在一个包(文档)中寻找一个产品(子文档)
Packages.find({_id : req.body.packId, "products._id" : req.body.prodId})
.exec(function(err, result){
if(err) throw err;
// make sure the result array exists and is not empty
if(result && result.length > 0) {
// make sure product array exists and is not empty
if(result.products && result.products.length > 0){
res.json(result);
}
}
});
我注意到我不能这样做:
if(result.products.length > 0)
如果没有产品,节点将崩溃,因为它无法确定未定义的“长度”。
我的问题是:有没有更好的方法来做到这一点?
解决方案
看起来您已经在检查 products_id,所以如果它被返回,它永远不应该为 null。
另一种方法是检查该字段是否已填充到查询中。
db.Packages.find({ "products.": { $exists: true, $ne: null } })
您可以在查询本身中进行检查,这样您就不必检查代码。
推荐阅读
- html - 带有图像和文本的六边形
- python - 不兼容类型:__main__.TestClass;预期的例子.TestClass; 将“self”传递给另一个模块
- javascript - ember-power-select 自定义搜索操作并使用外部数据“选择”
- java - 如何使用过滤的 RecyclerView 和 OnClickListener 从 ArrayList 中删除项目
- sql - 如何总结所有行的总数?
- jquery - Bootstrap 4 工具提示仍然存在,看起来很糟糕
- c++ - 带有任何算术运算符的常量操作数的顺序是否会影响优化?
- json - 使用python将多个csv文件转换为json
- c# - 如何从 Generic 中获取值
在 foreach 循环中 - android - FFMPEG 显示错误,例如无法找到合适的文本输出格式