JavaEar 专注于收集分享传播有价值的技术资料

MongoDB检查属性是否存在(以及子属性) (MongoDB check if a property exists (and a child property))

Is there a more conventional way to check if a property and a child property exists in a MongoDB document?

Right now I'm doing this to make sure it doesn't error when one of the properties or the whole document doesn't exist.

//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 is to see if sent is set to true. If it is I don't want to execute doSomething();

2个回答

    最佳答案

  1. 英文原文

    Try this:

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

    Although I'm not entirely sure what you're trying to do, as your code appears to be checking if the properties "credit" and "credit.sent" do not exist. If that's what you're looking for, then just change the $exists entry to false above.


    中文翻译

    试试这个:

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

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

    Try this:

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

    Although I'm not entirely sure what you're trying to do, as your code appears to be checking if the properties "credit" and "credit.sent" do not exist. If that's what you're looking for, then just change the $exists entry to false above.

    试试这个:

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

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

  2. 参考答案2
  3. EDIT : Realized the solution that @richsilv proposed is probably better depending on what you're trying to achieve. I'll let my answer if that's of any use to someone.

    1) Using pure JS, not really. You could refactor your code to store Donate.findOne({'debit.id': debitID}) in a variable though. This would look like this :

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

    It looks like you messed up with the ! operator : if you want to check for existence this is unneccessary, ! is used to check for inexistence.

    2) You could use another language on top of JS that provides syntactic sugar.

    Example using Coffeescript :

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