首页 > 解决方案 > 处理 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)

如果没有产品,节点将崩溃,因为它无法确定未定义的“长度”。

我的问题是:有没有更好的方法来做到这一点?

标签: javascriptnode.jsmongodbmongoose

解决方案


看起来您已经在检查 products_id,所以如果它被返回,它永远不应该为 null。

另一种方法是检查该字段是否已填充到查询中。

db.Packages.find({ "products.": { $exists: true, $ne: null } })

您可以在查询本身中进行检查,这样您就不必检查代码。


推荐阅读