0

I am trying to count the number of models in a collection based on a property:

I have an upvote model, that has: post (objectId) and a few other properties.

First, is this good design? Posts could get many upvotes, so I didn’t want to store them in the Post model.

Regardless, I want to count the number of upvotes on posts with a specific property with the following and it’s not working. Any suggestions?

upvote.count({‘post.specialProperty’: mongoose.Types.ObjectId(“id”), function (err, count) {
    console.log(count);
});
2
  • can you show your current data model? Commented Nov 5, 2015 at 17:48
  • @inspired i have a post schema that has a property of type object id. I have a up vote schema that has a property "post" that is the object id of the post. Commented Nov 5, 2015 at 17:53

1 Answer 1

3

Post Schema Design

In regards to design. I would design the posts collection for documents to be structured as such:

{
    "_id" : ObjectId(),
    "proprerty1" : "some value",
    "property2" : "some value",
    "voteCount" : 1,
    "votes": [
        {
            "voter": ObjectId()// voter Id,
            other properties...
        }
    ]
}

You will have an array that will hold objects that can contain info such as voter id and other properties.

Updating

When a posts is updated you could simply increment or decrement the voteCountaccordingly. You can increment by 1 like this:

db.posts.update(
        {"_id" : postId},
        {
            $inc: { voteCount: 1},
            $push : {
                "votes" : {"voter":ObjectId, "otherproperty": "some value"}
            }
        }
)

The $inc modifier can be used to change the value for an existing key or to create a new key if it does not already exist. Its very useful for updating votes.

Totaling votes of particular Post Criteria

If you want to total the amount for posts fitting a certain criteria, you must use the Aggregation Framework.

You can get the total like this:

db.posts.aggregate(
        [
            {
                $match : {property1: "some value"}
            },
            {
                $group : {
                    _id : null,
                    totalNumberOfVotes : {$sum : "$voteCount" }
                }
            }
        ]
)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! For the up vote storing in a post -- should I still keep the up vote model, and store an array of up votes in the post?
@user1947561 Can you put your vote model in your question and format it like the model I showed you so I can understand your model better?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.