Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB check if a property exists (and a child property)

Tags:

mongodb

meteor

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();

like image 781
JoshJoe Avatar asked Oct 16 '14 19:10

JoshJoe


2 Answers

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.

like image 197
richsilv Avatar answered Nov 05 '22 23:11

richsilv


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()
like image 2
saimeunt Avatar answered Nov 05 '22 23:11

saimeunt