0

I've got a simple poll trying to update the vote counter every time someone upvte it.

I tried using $inc but it has not effect. therefore it does return which supposed to be the updated poll/ poll after the vote counter is updated, but it just returns the same one without increasing anything at all.

What am i doing wrong?

 app.patch('/voting/:id', (req, res) => {
      let userVote = req.body.votes;

  Poll_Schema_Model.findByIdAndUpdate({ "_id": '5b070f512a28d70eb0abaa51' }, { $inc: { "poll[0].votes":userVote } }, { new: true }, (err, newPoll) => {
    res.status(200).send(newPoll);
  })
    .catch(() => {
      res.status(400).send();
    });

});

the newPoll results in :- (note that votes is defaulted to 0)

{
    "_id": "5b070f512a28d70eb0abaa51",
    "_creator": "5b04aba0ee81bb26182b2267",
    "poll": [
        {
            "votes": 0,
            "_id": "5b070f512a28d70eb0abaa52",
            "option1": "FIRST OPTIONNN",
            "option2": "SECOND OPTIONN"
        }
    ],
    "__v": 0
}

My schema :-

const Poll_Schema = new mongoose.Schema({
    _creator: {
        type: mongoose.Schema.Types.ObjectId
    },
    poll: [{
        option1: {
            type: String,
            maxlength: 20,
            minlength: 3
        },
        option2: {
            type: String,
            maxlength: 20,
            minlength: 3
        },
        votes: {
            type: Number,
            minlength: 1,
            default:0
        }
    }]
});
ANUBIS
  • 666
  • 1
  • 9
  • 20

1 Answers1

1

The syntax for referencing array item is different, you should specify position after dot like poll.0.votes instead of [0]. So your code should look like this:

app.patch('/voting/:id', (req, res) => {
   let userVote = req.body.votes;

   Poll_Schema_Model.findByIdAndUpdate({ "_id": '5b070f512a28d70eb0abaa51' }, { $inc: { "poll.0.votes":userVote } }, { new: true }, (err, newPoll) => {
     res.status(200).send(newPoll);
   })
     .catch(() => {
       res.status(400).send();
     });
});
mickl
  • 48,568
  • 9
  • 60
  • 89
  • I searched in older posts and they used `[0]`. but anyways it does work by `poll.votes` (no idea why it does work now that i tried before and it didnt) not `poll.0.votes` because that creates a new object called `"0":{"votes":1}` Thanks for helping. – ANUBIS May 24 '18 at 19:42
  • @SharlSherif it will create a property with key `"0"` if poll is an object. In your example it is an array. Maybe you have both objects and arrays under `poll` in your collection ? – mickl May 24 '18 at 19:47
  • this what happens when i use `poll.0.votes` `{ "_id": "5b0715daddfddb28f8c44f7f", "_creator": "5b04aba0ee81bb26182b2267", "poll": [ { "0": { "votes": 18 }, "votes": 17, "_id": "5b0715dbddfddb28f8c44f80", "option1": "FIRST OPTIONNN", "option2": "SECOND OPTIONN" } ], "__v": 0 }` – ANUBIS May 24 '18 at 19:55