I have a movie review website. I have two collections in my mongo db, one for my movie reviews, and one for reviews submitted by users.
Whenever a user submits their own review, I want to increment the variable userReviewCount within the collection of my reviews.
I'm using mongoose and running everything within javascript:
function saveUserReview(review) {
collections.ReviewModel.findOne(
{ 'filmId': review._filmId.toNumber() },
function(err, result) {
if (err) throw err;
currentCount = result.userReviewCount;
currentCount++;
});
collections.ReviewModel.update(
{ 'filmId': review._filmId.toNumber() },
{ $set: { "userReviewCount": currentCount } },
function(err, res) {
if (err) throw err;
console.log("Result of update:" + res);
});
So this function is called whenever a user submits a review. First, it uses findOne to find my review by its Id, and fetches the current value of userReviewCount. Then, it increments this by 1, and adds it back to the collection.
But what is super weird, is that the $set thing only seems to work every other time I call the function. The first time I call it the variable userReviewCount stays at 0, the second time I call it it goes to 1, the third time it stays at 1, the fourth time it goes to 2 and so forth. I cannot get my head around why it is operating like this. To debug I outputed the res to the console, but the result is always "Result of update:[object Object]" Which gives me no information.
Does anyone have any ideas how I can debug this? I've thought of everything.