Embedded document vs reference in mongoose design model?

前端 未结 2 714
失恋的感觉
失恋的感觉 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条回答
  •  猫巷女王i
    2020-12-13 01:52

    Personally I like to do references in situations like yours. In this way I can get a comment from a user, a user from a forum, a forum from a comment, a forum from a user, etc. without worrying about doing complicated embedded document queries. I don't even bother storing embedded reference documents. If there is a one to many relationship between a forum and comments then I would store a forum reference on the comment and no comment reference on the forum because when you add/remove comments from the comments collection you then also have to go remove the embedded reference document from the comments collection on the forum.

    I can query for a forum from a comment using the forum reference and I can get all comments for a forum by querying the comments collection for that forum reference (which is just an ID number until mongoose populates it behind the scenes for you).

提交回复
热议问题