如何调试MongoDB错误“order.addresses.setup是未定义的”?

时间:2017-11-27 11:35:51

标签: javascript mongodb shell mongodb-query robo3t

db.getCollection('order').find({bundleProducts:{$elemMatch:{id:"5720a0ce7709"}}}).forEach(
function(order){ print(
    "invoice addresses: " + order.addresses.invoice.city + "," +
    " delivery addresses: "+ order.addresses.delivery.city+","+
    " setup addresses: "+ order.addresses.setup.city+","); }) ;

当我运行上述问题时

无法执行脚本。

Error:
TypeError: order.addresses.setup is undefined :
@(shell):5:1
DBQuery.prototype.forEach@src/mongo/shell/query.js:501:1
@(shell):1:1

我收到了一个错误。 如果安装地址为空,我该如何编写查询?

1 个答案:

答案 0 :(得分:0)

您似乎正在尝试访问非现有字段(setup),这就是您收到错误的原因。如果您要排除不包含的文档,可能需要使用$exists运算符setup字段,这是一个例子:

db.getCollection('order').find({
    bundleProducts: {
        $elemMatch: { id: "5720a0ce7709" }
    },
    "addresses.setup": { $exists: true }
}).forEach( function(order){ print(
    "invoice addresses: " + order.addresses.invoice.city + "," +
    " delivery addresses: " + order.addresses.delivery.city + ","+
    " setup addresses: " + order.addresses.setup.city + ","); 
});