Alejandro
Alejandro

Reputation: 2324

Mongoose: $inc not working

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

Taken from what I was advised here in this StackOverFlow(Mongoose - Increment a value inside an array of objects), I changed the format of poll at ease to accommodate what was recommended.

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?

***update This is snippet of how I am creating documents

  let labelOptions = {}; <=== creating object literal to hold as placeholder
  const title = req.body.title;
  const description = req.body.description;
  req.body.labelOptions.split(/,\s*/).map( prop =>{
    labelOptions[prop] = 0 // set counter to default 0
  })

  const poll = new Poll({
    title: title,
    description: description,
    labelOptions: labelOptions,
    date: moment().format('MMM D, YYYY')
  });

  poll.save(function(err) {
    if (err) { return next(err); }
    res.json({ message : 'Poll added!'})
  });

Upvotes: 0

Views: 1471

Answers (1)

Alejandro
Alejandro

Reputation: 2324

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

Source: 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)
    }
  )

Upvotes: 1

Related Questions