I'm trying to update a file in my mongo document by it's index. I've managed to do it by explicitly providing the index in the query but I want the index to be variable which I can change with each request.
So I know this works:
const updateVote = await Polls.findOneAndUpdate(
{
"_id": ObjectId(pollId)
},
{
"$inc": {
"options.1.option.votes":1
}
}
)
The 1 in options.1 is what I want to be dynamic. I tried the following but it does not work
const query = "options."+pollIndex+".option.votes"
try{
const updateVote = await Polls.findOneAndUpdate(
{
"_id": ObjectId(pollId)
},
{
"$inc": {
query:1
}
}
)
The following is the full file I am trying to update
{
"_id": "61b7342e3dcde035fcbacef9",
"username": "johnboy",
"title": "This is me testing the vote system",
"description": "Hello, this is a sample description",
"options": [
{
"option": {
"name": [
"sample text for option1"
],
"votes": 25
}
},
{
"option": {
"name": [
"sample text for option2"
],
"votes": 31
}
}
],
"whoVoted": [
{
"username": "option index will go here"
},
{
"username": "option index will go here"
}
],
"comments": [
{
"sampleUser": {
"comment": "sample comment",
"date": "Mon Dec 13 2021 22:23:18 GMT+1030 (Australian Central Daylight Time)"
}
}
],
"createdAt": "2021-12-13T11:53:18.816Z",
"updatedAt": "2021-12-14T00:07:49.783Z",
"__v": 0
}
I'm fairly new to mongo/mongoose. Any help is appreciated. thank you!