简体   繁体   English

处理MongoDB查询结果中不存在的子文档的最佳方法

[英]Best way to handle non-existent sub-documents in MongoDB query results

I know this question has been asked before in some shape or form but I am looking for the best way to handle query results without a lot of if statements. 我知道这个问题以前曾以某种形式或形式被问过,但我正在寻找无需大量if语句即可处理查询结果的最佳方法。

Let's say I am looking for a product (sub-document) in a package (document) 假设我要在包装(文档)中寻找产品(子文档)

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);
           }
          }
        });

I noticed I cannot do: 我注意到我做不到:

if(result.products.length > 0)

If there is no product, node will crash since it cannot determine 'length' of undefined. 如果没有产品,则节点将崩溃,因为它无法确定未定义的“长度”。

My question is: Is there a better way to do this? 我的问题是:还有更好的方法吗?

It looks like you are already checking the products_id, so it should never be null if it is returned. 看起来您已经在检查products_id,因此,如果返回,则永远不能为null。

Another way you could do it is by checking that the field is populated in the query. 您可以执行的另一种方法是,检查查询中是否填充了该字段。

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

You can make the check in the query itself so that you don't have to check in code. 您可以在查询本身中进行检查,从而不必检入代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM