DBRef 可以包含附加字段吗?
我在使用 MongoDB 时遇到过几种需要使用 DBRef 的情况。但是,我还想在 DBRef 本身中缓存引用文档中的一些字段。
{$ref:'user', $id:'10285102912A', username:'Soviut'}
例如,即使引用了用户文档,我也可能希望用户名可用。这将为我提供单一文档方法的所有好处;查询速度更快,并且无需在代码中进行手动取消引用。同时允许我在有意义的地方使用参考文献。
这个想法是,当引用的文档更新时(例如,用户更改其名称),我的业务层可以自动更新引用它的所有文档。
最后,我想知道在 DBRef 上存储附加字段是否被认为是一种好的形式?它会破坏任何东西吗?每次重写引用时我都会丢失数据吗?像 pymongo 这样的驱动程序会支持它吗?
I've encountered several situations when using MongoDB that require the use of DBRefs. However, I'd also like to cache some fields from the referenced document in the DBRef itself.
{$ref:'user', $id:'10285102912A', username:'Soviut'}
For example, I may want to have the username available even though the user document is referenced. This would provide me all the benefits of a single document approach; Faster querying and eliminating the need to do manual dereferencing in my code. While at the same time allowing me to use references where they make sense.
The idea being that when the referenced document is updated (a user changes their name, for example) my business layer can automatically update all the documents that reference it.
Ultimately, I'm wondering if it's considered good form to store additional fields on my DBRefs? Will it break anything? Will I lose my data each time a reference is rewritten? Will drivers like pymongo support it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
拥有单独的“缓存”和“引用”字段可能会更干净......这取决于您的数据是什么样的。
你可以,但如果你小心的话就不会。如果要更新数据库引用子对象,只需确保更新要更新的特定字段,而不是覆盖整个子对象。
请记住引用,因为它们只是普通对象。数据库引用是一个标准,而不是特殊类型。
驱动程序的取消引用助手仍然可以工作。助手只需使用 $ref 和 $id 字段执行 findOne 操作。
It might be cleaner to have separate "cached" and "ref" fields... it depends one what your data is like.
You could, but not if you're careful. If you're updating the DB ref subobject, just make sure you're updating the specific fields you want updated, not overwriting the whole subobject.
Remember that references as they are just normal objects. The database reference is a standard, not a special type.
The driver's dereferencing helpers will still work. The helpers just do a findOne with the $ref and $id fields.