user9085083
user9085083

Reputation:

MongoDB, increment field with condition

Is it possible, using mongoose middleware, to increment two fields one with a condition and the other without? In this case i want to increment "stats.ratings" by one, if the user inserts an input greater than 0, else increment zero.

"stats.answered" always increments one

See code below

 module.exports.updateStats = function (req, res) {

            var rating = parseInt(req.body.rating, 10);
            var wasRated;
            if (rating > 0) {
                wasRated = true;    
            } else wasRated = false

            Collection.findOneAndUpdate({
                        _id: req.body._id
                    }, {
                        $cond: {
                            if: wasRated,
                            then: {
                                $inc: {
                                    "stats.answered": 1,
                                    "stats.ratings": 1
                                }
                            },
                            else: {
                                $inc: {
                                    "stats.answered": 1,
                                    "stats.ratings": 0
                                }
                        }
                    }
                },
                function (err, doc) {
                    if (err)
                        throw err;
                    res.status(200);
                })
        }

Upvotes: 0

Views: 2943

Answers (1)

dnickless
dnickless

Reputation: 10918

What you can do is this:

// define the default case
var update = {
    $inc: {
        "stats.answered": 1
    }
};

if(parseInt(req.body.rating, 10) > 0) {
    // override default in some cases
    update = {
        $inc: {
            "stats.answered": 1,
            "stats.ratings": 1
        }
    }
}

and then

Collection.findOneAndUpdate({
            _id: req.body._id
        }, update,
    function (err, doc) {
        if (err)
            throw err;
        res.status(200);
    })

}

Upvotes: 2

Related Questions