是否有更传统的方法来检查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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
!Donate.findOne({'debit.id': debitID}).credit.sent是看看sent是否设置为true.如果是,我不想执行doSomething();
试试这个:
Donate.findOne({'debit.id': debitId, 'credit.sent': {$exists: true}});
Run Code Online (Sandbox Code Playgroud)
虽然我不完全确定你要做什么,因为你的代码似乎在检查属性"credit"和"credit.sent" 是否不存在.如果这是您正在寻找的,那么只需将$exists条目更改为false上面.