Embedded document vs reference in mongoose design model?

前端 未结 2 710
失恋的感觉
失恋的感觉 2020-12-13 01:26

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 othe

2条回答
  •  独厮守ぢ
    2020-12-13 01:42

    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:

    Embedding:

    • Small subdocuments
    • Data that does not change regularly
    • Eventual consistency is acceptable
    • Document that grow by a small amout
    • Data that you will often need to perform a second query to fetch
    • Fast reads

    Referencing:

    • Large subdocuments
    • Volatile data
    • Immediate consistency is necessary
    • Document that grow a large amount
    • Data that you will often exclude from results
    • Fast writes

    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.

    Hope it helps!

提交回复
热议问题