【问题标题】:MongoDB check if a property exists (and a child property)MongoDB 检查属性是否存在(和子属性)
【发布时间】:2014-10-16 19:25:55
【问题描述】:

是否有更常规的方法来检查 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是看send是否设置为true。如果是我不想执行doSomething();

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    试试这个:

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

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

    【讨论】:

    • 谢谢,效果很好。我修复了代码,使其正确读取。这个!Donate.findOne({'debit.id': debitID}).credit.sent的原因是看send是否设置为true。如果是我不想执行doSomething();
    【解决方案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()
    

    【讨论】:

    • 感谢您发现我的错误和您的回答。我不知道 MongoDB 函数可以像 javascript 函数一样使用。这仍然是一个有用的答案,我很欣赏 Coffeescript 示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 2011-02-01
    相关资源
    最近更新 更多