1

I have been thinking of using Node and MongoDb for a ratings system for an Android app, so far I have implemented Create, Update and Delete fine but am at a loss as to what to do when I want to get the average rating back from the DB. Here is the data structure I gave decided upon:

[
  {
    "_id": "1",
    "ratings": [
      {
        "value": "5",
        "user": "CoolUser1"
      },
      {
        "value": "4",
        "user": "CoolUser2"
      }
    ]
  },
  {
    "_id": "2",
    "ratings": [
      {
        "value": "4",
        "user": "CoolUser3"
      },
      {
        "value": "2",
        "user": "CoolUser4"
      }
    ]
  }
]

Basically what I need is the average value in ratings for a given _id.

Here is the Update method I am using to give a sense of how I have setup the mongoDB connection:

exports.updateRating = function(req, res) {
    var id = req.params.id;
    var rating = req.body;
    console.log('Updating a rating: ' + id);
    console.log(JSON.stringify(rating));
        ratings.update({'_id': id}, 
                        {$push: rating}, 
                        {upsert:true}, 
                        function(err, result) {
                            if (err) {
                                console.log('Error updating rating: ' + err);
                                res.send({'error':'An error has occurred'});
                            } else {
                                console.log('' + result + ' document(s) updated');
                                res.send(rating);
                            }
                        }
        );
}

1 Answer 1

9

Is it critical to store ratings.value as a string?

This will work, but only if you convert rating to number before safe

ratings.aggregate([
   { $match: { _id: id } },
   { $unwind: '$ratings' },
   { $group: { _id: null, avg: { $avg: '$ratings.value' } } }
], function(err, result) {
    console.log(result);
    db.close();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Think you, works perfectly when I store the ratings as a number

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.