Mongoose population - callback vs exec

Sax

On Node.js/Mongoose/Mongo is

SomeModel.findOne({_id: id}, callback).populate('ref')

equivalent to

SomeModel.findOne({_id: id}).populate('ref').exec(callback)

"ref" is single doc (not an array).

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

robertklep

I don't know the internals, but I'd say they are not the same.

The first probably does this:

  • find the document
  • call the callback with the document
  • populate the ref (this is done through a separate query)

The second probably does this:

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

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related