node.js - Mongoose population - callback vs exec -


on node.js/mongoose/mongo is

somemodel.findone({_id: id}, callback).populate('ref') 

equivalent

somemodel.findone({_id: id}).populate('ref').exec(callback) 

"ref" single doc (not array).

the problem using first syntax "child" document randomly not populated when callback called.

i don't know internals, i'd not same.

the first this:

  • find document
  • call callback document
  • populate ref (this done through separate query)

the second this:

  • find document
  • populate ref
  • call callback when ref has been resolved

the randomness you're witnessing because "populate ref" call, when fast enough, may populate document before use in callback. in other words: race condition.


Comments