findOne immediately following update

I sometimes get a bit mixed up about collections and concurrency. If I do a collection.update(_id, mod) and immediately follow it up with collection.findOne(_id), is it guaranteed that I will always get the updated document?

From my point of view it depends on:

  1. .update and .findOne are at same client?
  2. why and how would you do .update immediate followed by findOne?
    If this is at same function, why would you use findOne, you still have the record from .update?
  3. client - server latency if using server / client methods for update

So I think, if you make the correct use-case, the updated data is immediately available. Maybe you like to describe your case a bit more.

Let’s work with the premise that we are on the server with the second call following directly on the next line.

I see two reasons for doing this, in cases where we need the changed document:

  1. update only needs an _id (possibly given as a parameter to a Meteor method) and a modifier, so we may not have the document handy.
  2. The update may involve various hooks/behaviours or allow calls that transform the documents, meaning that its final state can’t easily be surmised without actually retrieving it back from the collection.

Yes, in that case you describe, the updated document will be returned by the findOne on the next line (unless some of the hooks run something asyncronously that might affect the document, which is not usually the case).

1 Like

This another “depends on” if you maybe have added some observers etc. but as @babrahams already stated - if you have not build special conditions the findOne should get you latest data.

1 Like