Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB检查属性是否存在(以及子属性)_Mongodb_Meteor - Fatal编程技术网

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

MongoDB检查属性是否存在(以及子属性),mongodb,meteor,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': debitI

是否有更常规的方法来检查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();
        }
    }
}

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

编辑:意识到@richsilv提出的解决方案可能更好,这取决于您试图实现的目标。如果我的回答对某人有用的话,我会告诉你的

1) 使用纯JS,不是真的。您可以重构代码,将
genate.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()
试试这个:

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

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

谢谢,这非常有效。我修正了代码,使其正确读取。这是为什么
!devote.findOne({'debit.id':debitID}).credit.sent
用于查看sent是否设置为true。如果是,我不想执行
doSomething()谢谢你抓住我的错误,谢谢你的回答。我不知道MongoDB函数可以像javascript函数一样使用。这仍然是一个有用的答案,我很欣赏Coffeescript的例子。