检查是否存在mongo数据密钥

时间:2015-04-10 11:22:30

标签: node.js mongodb

我有一些产品数据,其中某些产品没有关键" images.cover" 。 现在当我尝试打印所有数据时显示错误

  

无法阅读财产'封面'未定义的。

因此,如果images.cover键不存在,那么我尝试制作,然后只添加var cover = '';其他images.cover值。我使用的是nodejs和mongodb

1 个答案:

答案 0 :(得分:0)

从错误消息:

  

无法阅读财产'封面'未定义的

您可以将故障产品文档中的错误源缩小到以下三个属性中的任何一个:

  1. 该文档没有images字段(因此未定义的对象),
  2. images字段可以为null,
  3. covers密钥可能也不存在。
  4. 让我们考虑一个最小测试用例,其中样本集合包含上述三个+一个带有images.cover密钥集的文档:

    db.product.insert([
        /* 0 */
        {
            "_id" : 1,
            "image" : {
                "cover" : "test1",
                "url" : "url1"
            }
        },
    
        /* 1 */
        {
            "_id" : 2,
            "image" : {
                "url" : "url2"
            }
        },
    
        /* 2 */
        {
            "_id" : 3
        },
    
        /* 3 */
        {
            "_id" : 4,
            "image" : {
                "cover" : null,
                "url" : "url4"
            }
        }
    ]);
    

    在mongo shell中,您可以使用本机JavaScript方法或使用mongodb的$exists运算符来检查密钥是否存在。对于前者,您可以尝试:

    var cover = "", covers = [];
    db.product.find().forEach(function (doc){    
        var cover = "";
        if ((doc.image !== undefined) && (typeof(doc.image.cover) !== "undefined") && (doc.image.cover !== undefined)){
            cover = doc["image"].cover;        
        }  
        covers.push(cover);     
    });
    print(covers); /* will print to mongo shell:
    {
        "0" : "test1",
        "1" : "",
        "2" : "",
        "3" : null
    }
    */
    

    使用$exists运算符并将其值设置为true,这将搜索包含该字段的文档,包括字段值为null的文档。因此,在您的示例中使用此路由可能不起作用,因为您还要为不匹配的文档分配cover变量:

    var cover = "", covers = [];
    db.product.find({ "image.cover": {$exists : true} }).forEach( function(doc) { 
        covers.push(doc["image"].cover);
    });
    print(covers); /* this will print to mongo shell:
    {
        "0" : "test1",
        "1" : null
    }
    */