Search code examples
mongodbmongoosemongoose-populateeventual-consistency

mongoose eventual consistency when populating virtual fields


I have a schema with a virtual reference to a different model:

User.virtual('stuffs', {
  ref: 'Stuff',
  localField: '_id',
  foreignField: 'owner',
  options: {},
});

When a new user registers, I also generate some related stuff for it, and I want to return the user-object with the stuffs field populated, so I do something like:

const user = await (new User(...).save());
const stuff = await (new Stuff({ owner: user._id }).save());
res.json({ user: (await user.populate('stuffs').execPopulate()).toObject({ virtuals: true }) });

I assume that the populate function operates by querying the stuff collection for a document where the owner is user._id, just like the one that was saved in the command above.

I've read that Mongodb is only eventually-consistent, does that mean that the query might fail and not find the stuff that was just saved? If so, what are the chances? Do I really need to verify that the population succeeded? Should I add a retry-loop with several attempts?

Thanks.


Solution

  • You should be fine, unless you are reading from a secondary-replica. From https://www.mongodb.com/faq#consistency:

    MongoDB is consistent by default: reads and writes are issued to the primary member of a replica set. Applications can optionally read from secondary replicas, where data is eventually consistent by default. Reads from secondaries can be useful in scenarios where it is acceptable for data to be slightly out of date, such as some reporting applications. Applications can also read from the closest copy of the data (as measured by ping distance) when latency is more important than consistency.

    Therefor, unless you write in one database and read from a replica of it, you should not run into problems populating.