填充虚拟字段时的猫鼬最终一致性

mongoose eventual consistency when populating virtual fields

我有一个架构,其中 虚拟 引用了不同的模型:

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

当一个新用户注册时,我也会为它生成一些相关的 stuff,我想 return 带有 stuffs 的用户对象填充字段,所以我会做类似的事情:

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 }) });

我假设 populate 函数通过查询 stuff 集合来查找所有者为 user._id 的文档,就像之前的文档一样保存在上面的命令中。

我读到 Mongodb 只是最终一致的,这是否意味着查询可能会失败并且找不到刚刚保存的 stuff?如果是这样,机会有多大?我真的需要验证填充是否成功吗?我应该添加多次尝试的重试循环吗?

谢谢。

你应该没问题,除非你是从二级副本读取的。来自 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.

因此,除非您写入一个数据库并从它的副本读取,否则您不应该 运行 遇到填充问题。