Here is my Schema,
var ProductSchema = new Schema({
_id: {
type: Schema.Types.ObjectId,
ref: "User"
},
overall_rating: {
average: {
type: Number,
default: null
},
rate_count:{
type: Number,
default: 0
}
}
});
What I need to do is to update "overall_rating.average" using only one mongoose query. ( cannot use two queries because of concurrency issues.)
If consider following terms
current_avg => current value in "overall_rating.average"
current_rate_count=> current value in "overall_rating.rate_count"
new_rating => new rating value
Query should be something like this
Product.findOneAndUpdate({ '_id': req.body.product_id }, { $set: { 'overall_rating.average': (current_avg*current_rate_count + new_rating)/(rate_count+1) }, {$inc: { overall_rating.rate_count: 1 }} }, { new: true }).exec(function(err, product) {
if (err) {
console.log(err);
return res.json({ success: false, msg: err });
} else {
return res.json({ success: true, obj: product});
}
});
It is a must to execute this as a one atomic query. So Cann't go with two steps (two queries)
Can anyone help me on this?