Waiting for collection search to complete before moving to dependent conditional


#1

Hi,

I’m a newbie, so this question might have been answered in one way or the other, but I wasn’t able to make sense of it neither on Stack Overflow, or here.

I want to search a collection for some data and in case it’s not present, I wish to add some data to another collection:

var tipCheck = PollingTable.findOne({tipId: tipId});

if(typeof tipCheck == 'undefined'){
   PriceCheck.insert({
	  symbolId: symbolId,
	  lastPrice: 'undefined',
	  lastPolled: 'undefined'
});

I think that because of Meteor’s asynchronous nature, the if condition is checked even before the result of the search query is returned. I was unable to figure out how to use Meteor.wrapAsync for this.

Any help would be appreciated. Thanks in advance!


#2

Actually, these queries are run in sync, so that should not be the issue. However, what is async is the subscriptions, so if you are doing this on the client, make sure your subscriptions are ready :wink: If it is on the server, it should work just fine.

Also, any particular reason you have this? They are already undefined by default, so having a string for that seems more work than it is worth.

lastPrice: 'undefined',
lastPolled: 'undefined'

#3

findOne is synchronous, so there shouldn’t be any problem.
I think it returns null when nothing is found. If I am right, your if test should be replaced by if (tipCheck !== null) or if (tipCheck).


#4

I don’t think this is the case, no. Easy to test though.


#5

@jorgeer @Steve Thanks for the quick replies guys! I went through my code again, and you guys are absolutely right. I must have been making some other silly error.

@jorgeer I thought initialing these fields even with an ‘undefined’ value would be a better practice, since I would be checking them later on and reassigning values. But on second thoughts, perhaps not so much. Thanks for pointing that out as well.


#6

If you want them defined, but have no value, I would rather use null, as it is a falsy value and suited to represent values not yet set.