ishay m
ishay m

Reputation: 189

How is it possible to increase value for dynamic property in mongoDB

I'm trying to icrease a dynamic value on my database which depends on user's mark, lets say there is a "vote" object with 3 parameters:

//data structure : 
_id : someObjectId,
gameId : someObjectId,
votes : { 
a: 0,
b: 0,
c: 0
}


userVote = { vote: 'b', gameId: '5cf3c5cc1c9d44000053defb' }

function addVote(userVote) {
    userVote.gameId = new ObjectId(userVote.gameId)
    return mongoService.connect()
        .then(db => {
            const collection = db.collection('totalVotes');
            return collection.updateOne(
                { gameId: userVote.gameId },
                { $inc: { "votes[userVote[vote]":1 } }
             )
        })
}

So, of course, the "inc" line isn't working that way, how is it possible to do this?

Thanks.

Upvotes: 0

Views: 40

Answers (1)

B. Fleming
B. Fleming

Reputation: 7230

MongoDB has no way of knowing what votes[userVote[vote] even means (syntax error aside). It has no access to your client-side JavaScript. If you want to set this dynamically, change your $inc line to the following:

{ $inc: { ["votes." + userVote.vote] : 1 } }

If the bracket notation above is not supported, you can try something like the following instead:

let incVote = {};
incVote["votes." + userVote.vote] = 1;
return collection.updateOne(
    { gameId: userVote.gameId },
    { $inc: incVote }
);

Upvotes: 1

Related Questions