2014-10-16 69 views
4

是否有更传统的方法来检查MongoDB文档中是否存在属性和子属性?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是看是否发送设置为true。如果是我不想执行doSomething();

回答

5

试试这个:

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

虽然我不能完全确定你想要做什么,因为如果出现的属性查收代码“credit”和“credit.sent”不存在存在。如果这就是你想要的,那么只需将上面的$exists条目更改为false即可。

+0

谢谢,这工作很好。我修复了代码,使其正确读取。这个'''!Donate.findOne({'debit.id':debitID})。credit.sent'''的原因是查看发送是否设置为true。如果是我不想执行'''doSomething();''' – JoshJoe 2014-10-16 20:38:06

+0

啊,现在有道理。 – richsilv 2014-10-16 20:39:14

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() 
+0

感谢您捕捉我的错误,并为您的答案。我不知道MongoDB函数可以像JavaScript函数一样使用。这仍然是一个有用的答案,我很欣赏Coffeescript示例。 – JoshJoe 2014-10-16 20:40:09

相关问题