Mongoose: $inc not working [SOLVED]

I am not sure what the problem is, as I’ve read numerous examples.

So I was able to create a document format as so:

{
  "_id": "584c4160b3b22e1bdad59bce",
  "title": "Food",
  "description": "test",
  "labelOptions": {
    "burger": 29,
    "coffee": 44,
    "pizza": 23
  },
  "date": "Dec 10, 2016",
  "__v": 0
}

Here’s what I have so far:

Poll Model

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const pollData = new Schema({
  title: String,
  description: String,
  labelOptions: {},
  date: String
})

module.exports = mongoose.model('PollData', pollData)

Using express and mongoose, here’s what I have:

app.put('/polls/:id', function(req, res){
  let id = req.params.id;
  let labelOption = req.query.labelOption;
  let query = `labelOptions.${labelOption}`
  Poll.findByIdAndUpdate(
    id,
    {$inc: { query: 1 } },
    function(err, document){
      console.log(err)
      console.log(document)
    }
  )
})

In my terminal, I see that console.log(document it receives the document I was looking for but it does not update the value at all.

Am I setting up the Model correctly? Or does Mongoose does not support template strings?

Solved it!

After doing some research across the internet, I found the reason why it wasnt working: You can’t initialize objects with ‘dynamic’ keys.

Source: http://stackoverflow.com/questions/36418463/mongoose-update-on-a-string-variable-not-working

By knowing that, it was just a simple solution to initialize an literal object as so:

  let id = req.params.id;
  let labelOption = req.query.labelOption;
  let query =  "labelOptions." + labelOption
  let obj = {
    [query] : 1
  }
  Poll.findByIdAndUpdate(
    id,
    {$inc: obj },
    function(err, document){
      console.log(err)
      console.log(document)
    }
  )
2 Likes