MongoDB检查属性是否存在(以及子属性)

时间:2014-10-16 19:25:55

标签: mongodb meteor

是否有更常规的方法来检查MongoDB文档中是否存在属性和子属性?

现在我这样做是为了确保当其中一个属性或整个文档不存在时它不会出错。

//Check to see if the document exists
if(Donate.findOne({'debit.id': debitID})) { 
    //Check to see if the document has the property "credit"
    if(Donate.findOne({'debit.id': debitID}).credit){ 
        //Check to see if the object credit has the property sent
        if(!Donate.findOne({'debit.id': debitID}).credit.sent){
            doSomething();
        }
    }
}

!Donate.findOne({'debit.id': debitID}).credit.sent是查看sent是否设置为true。如果是,我不想执行doSomething();

2 个答案:

答案 0 :(得分:6)

试试这个:

Donate.findOne({'debit.id': debitId, 'credit.sent': {$exists: true}});

虽然我并不完全确定您要尝试做什么,因为您的代码似乎正在检查属性是否属于"信用"和" credit.sent" 不存在。如果这是您正在寻找的内容,那么只需将$exists条目更改为上面的false

答案 1 :(得分:2)

编辑:实现了@richsilv提出的解决方案可能更好,取决于您尝试实现的目标。如果对某人有任何用处,我会回答我。

1)使用纯JS,不是真的。您可以重构代码以将Donate.findOne({'debit.id': debitID})存储在变量中。这看起来像这样:

var donation=Donate.findOne({'debit.id': debitID});
if(donation && donation.credit && donation.credit.sent){
  doSomething();
}

看起来你搞砸了!运算符:如果你想检查是否存在这是不必要的,!用于检查是否存在。

2)你可以在JS之上使用另一种提供语法糖的语言。

使用Coffeescript的例子:

donation = Donate.findOne
  'debit.id': debitID
if donation?.credit?.sent
  doSomething()