我一直在考虑将 Node 和 MongoDb 用于 Android 应用程序的评分系统,到目前为止,我已经很好地实现了 Create、Update 和 Delete,但是当我想从D B。这是我决定的数据结构:
[
{
"_id": "1",
"ratings": [
{
"value": "5",
"user": "CoolUser1"
},
{
"value": "4",
"user": "CoolUser2"
}
]
},
{
"_id": "2",
"ratings": [
{
"value": "4",
"user": "CoolUser3"
},
{
"value": "2",
"user": "CoolUser4"
}
]
}
]
基本上我需要的是给定_id的评级平均值。
这是我用来了解我如何设置 mongoDB 连接的 Update 方法:
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);
}
}
);
}