问题描述
假设我正在使用 Node.js 和 mongoose 构建一个论坛.一个用户可以有多个论坛,一个论坛可以有多个评论.用户也可以邀请其他用户加入论坛.因此,我的问题是关于使用参考或嵌入文档的模型设计!
Let's say I am building a discussion forum using Node.js, and mongoose. A user can have multiple forums, and a forum can have multiple comments. A user can also invite other users to join a forum too. Thus, my question is about the model design either using reference or embedded document !
如果我使用嵌入式文档,它看起来像:
If I go with embedded document, It would look like:
var Comment = new Schema({ ... });
var Forum = new Schema({
title: {type: String},
content: {type: String},
comments: [Comment],
attendees: [User]
});
var User = new Schema({
name: {type: String},
email: {type: String},
forums: [Forum]
});
var Account = mongoose.model('Account', User);
使用上述设计时,我遇到了困难:当用户向论坛添加评论,而该论坛在我的论坛中时,我认为我无法在我的论坛列表中获得新评论的更新.我吗?你知道在这种情况下如何让嵌入的文档工作吗?
Using the above design, I struggled with: when a user adds a comment to a forum, and that forum is in my forums, I don't think I would be able to get update of a new comment in my forum list. Do I ? Do you know how to get the embedded document to work in this case?
因此,我考虑在 mongoose 中使用 reference.在这种情况下,我将有两个集合:帐户和论坛.在这种情况下,向论坛添加新评论不是问题.我说得对吗?
Thus, I was thinking of using reference in mongoose. In this case, I will have two collections: Account, and Forum. Adding a new comment to a forum is not a problem in this case. Am I right?
对于这个应用程序,参考会比嵌入文档更好吗?
Would reference be better than embedded document for this app?
提前致谢,
推荐答案
这主要取决于您将如何查询和更新数据.在这种情况下,一致性和文档大小也很重要.以下是关于何时引用或嵌入文档的一个很好的总结:
It depends mostly on how you're gonna query and update your data. Consistency and document size is also important in this case. Here's a good summary on when referencing or embedding documents:
嵌入:
- 小子文档
- 不定期更改的数据
- 最终的一致性是可以接受的
- 小幅增长的文档
- 您经常需要执行第二次查询来获取的数据
- 快速读取
参考:
- 大型子文档
- 易失数据
- 必须立即保持一致性
- 大量增长的文档
- 通常会从结果中排除的数据
- 快速写入
这是我读过的一本关于 mongo 的书的摘录.这些只是一般规则,但根据我的经验,使用它们可以让您在大多数情况下非常清楚是引用还是嵌入.
This is an exctract from a book on mongo I read. These are just general rules but from my experience, using them makes it very clear wether to reference or embed most of the times.
在这种情况下,我宁愿参考论坛.但请考虑您的所有要求.例如,如果您从用户引用论坛,并且需要查询特定论坛的所有用户,则在这种情况下查询可能会很慢.如果我是你,我会列出我需要的所有内容,然后使用一般规则在嵌入和引用的利弊之间找到平衡.
I would rather reference Forum in this case. But please consider all your requirements. For example if you reference Forum from User and you need to query all User of a particular Forum the query might be slow in this case. If I were you I would compose a list of everything I need and then using general rules would find a balance between pros and cons of embeding and referencing.
希望能帮到你!
这篇关于猫鼬设计模型中的嵌入式文档与参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!