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();
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With