Modelling blogs and ratings in mongodb and nodejs

前端 未结 1 577
礼貌的吻别
礼貌的吻别 2021-02-09 14:56

I have a blogs collection that contains title, body and agrregate rating that the users have given to them. Another collection \'Ratings\' whose schema has reference to the blog

相关标签:
1条回答
  • 2021-02-09 15:27

    A good practice with MongoDB (and other non-relational data stores) is to model your data so it is easy to use/query in your application. In your case, you might consider denormalizing the structure a bit and store the rating right in the blog collection, so a blog might look something like this:

    {
      title: "My New Post",
      body: "Here's my new post. It is great. ...",
      likes: 20,
      dislikes: 5,
      ...
      rates: [
        { client_id: (id of client), rate: 5 },
        { client_id: (id of another client), rate: 3 },
        { client_id: (id of a third client), rate: 10 }
      ]
    }
    

    The idea being that the objects in the rates array contains all the data you'll need to display the blog entry, complete with ratings, right in the single document. If you also need to query the rates in another way (e.g. find all the ratings made by user X), and the site is read-heavy, you may consider also storing the data in a Rates collection as you're doing now. Sure, the data is in two places, and it's harder to update, but it may be an overall win after you analyze your app and how it accesses your data.

    Note that you can apply indexes deep into a document's structure, so for example you can index News.rates.client_id, and then you can quickly find any documents in the News collection that a particular user has rated.

    0 讨论(0)
提交回复
热议问题