So, a little background about what I'm trying to create. I am trying to build a voting app, where a MongoDb database stores the options and the counters for each of those options to check how many times people have voted for each option. The data structure I have implemented looks like below.
_id:"57dfecfa3832360f46e183c2"
options:"iea, aoegboae, aoeugoa, ougr, gege"
options_counter:Object
0:0
1:0
2:0
3:0
4:0
__proto__:Object
title:"hr"
Each of those numbers [0,1,2,3,4] represents an option and the number after the colon represents the counter for each. My function to update the required counter is shown below
var fieldToIncrement = db.collection('polls').options_counter.field;
db.collection('polls').findOneAndUpdate(
{_id: user_id},
{$inc: {fieldToIncrement: 1}},
{upsert:false},
{returnNewDocument: true}
).toArray(function(err, doc){
if(err){
throw new Error(err);
}if(doc){
console.log(doc);
//callback(null, doc);
}
});
However, using the fieldToIncrement variable returns an error saying that cannot find property field of undefined. The variable field contains the number specifying the specific key of the options_counter object that needs to be incremented by 1. I have embedded the options_counter within the original document. My question is how do I set up the syntax so that MongoDb can find the specific key value pair within the options_counter object to update, and increment that counter by 1?
console.log(fieldToIncrement)to show its value. It's likely not what you think it is.