L
L
likejavascript2016-05-18 12:54:59
MongoDB
likejavascript, 2016-05-18 12:54:59

How to recalculate counters for a post?

I am developing a forum similar to Stackowerflow and want to consult with you on the best way to store counters: the number of ratings, views and the choice of the best answer.
I am using Nodejs/MongoDB. Right now I have two collections:
Posts :

[{
   _id: ObjectId(1),
   title: 'Untitled',
   content: 'empty'
}]

Votes:
[{ 
    _post: ObjectId(1),
    _user: ObjectId(...),
    vote: 1,        
}, {
    _post: ObjectId(1),
    _user: ObjectId(...),
    vote: 1,
}]

When a user votes on a post with ObjectId(1), the following request is sent:
Votes.create({_post: ObjectId(1), vote: 1}).exec(cb);

When getting a list of posts, I have to do several queries:
1. Query all posts sorted by creation date
2. Query all ratings for each post and add them to posts in nodejs.
When frequently requesting a list of posts, there will be problems in constantly recalculating counters, I would like to improve by recalculating saving the counter directly in the post:
[{
   _id: ObjectId(1),
   title: 'Untitled',
   content: 'empty',
   votes: 2
}]

But in this case, I need to somehow maintain data integrity and ensure that the actual counters in the post are updated based on the rating data in Votes.
This problem can be solved by embedding the scores as an array and storing it in posts, but MongoDB doesn't like to update large documents.
In general, advise a pattern for guaranteed recalculation of counters in a post, what can be used, queues, versioning or something else?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lega, 2016-05-18
@lega

I would think of this option (posts):

{
  votes: 15,
  vote: {
    user1: 1,
    user2: -1
  }
}

One request and recount and protection against re-voting, and selection with one request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question