Conrad
Conrad

Reputation: 96

How can I make sure that data from a certain Collection arrives before other data?

I have two collections, tableA and tableB. Documents in tableB have a field that corresponds to the _id in one document in tableA (basically, a foreign key). For example:

tableB.find({tableA_id: xxx}) // returns documents whose tableA_id is xxx

Now, I have an observeChanges listening to the tableA collection. If tableA has new or updated documents, I need to get documents from tableB with the new _ids:

tableA.find({}).observeChanges({
    changed: function(new, old) {
        tableB.find({tableA_id: new._id});
    }
    ...
});

However, sometimes, the update from tableA reaches the client first, even if I insert documents in tableB first.

// This is how I insert data in the server.
tableB.insert(...);
tableA.insert(...);

The updates from tableB arrive shortly after.

My current solution is basically to do a Meteor.call inside observeChanges, which gets the new data from the server manually, though it's inelegant. I also thought of calling a Meteor.setTimeout before getting the documents from tableB.

Is there any way that I can ensure that data from tableA will arrive first?

Upvotes: 0

Views: 73

Answers (1)

songololo
songololo

Reputation: 4964

Is it possible to clarify your schema design and why you are using two tables? There may be a simpler way to structure your schema, or to have one collection instead of two.

But lets assume that two separate collections are necessary: Have you tried creating a callback function?

e.g. create the callback function along these lines:

myFunctionName = function(arg1, arg2,...,callback){
  //run your first query here...
  //then run your callback function
  if (callback && typeof(callback) === "function") {  
    callback();
  }
});

Then you would call your function along these lines:

myFunctionName(arg1, arg2, ..., function(){
  // run your second query here...
  // note: this is your "callback" function
}

The code will run myFunctionName first - i.e. query 1 - then will run the callback function - i.e. query 2. You can pass variables from the parent function into the callback function, if you wish.

Upvotes: 1

Related Questions