You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

$inc对MongoDB文档无作用,投票计数更新失败求助

Fixing Your $inc Operation for the Voting System

Hey there! Let's get that vote counter working properly. The root issue here is how you're targeting the array field in your MongoDB update query.

The Problem

MongoDB doesn't support square bracket notation (poll[0].votes) when specifying fields in update operations. Your current query is trying to increment a field that MongoDB doesn't recognize as existing, so it leaves the default votes: 0 untouched.

The Fix

You need to use dot notation with the array index instead. Replace poll[0].votes with poll.0.votes in your $inc statement. Here's the corrected interface code:

app.patch('/voting/:id', (req, res) => {
  let userVote = req.body.votes;
  Poll_Schema_Model.findByIdAndUpdate(
    { "_id": '5b070f512a28d70eb0abaa51' },
    { $inc: { "poll.0.votes": userVote } }, // Fixed field path here
    { new: true },
    (err, newPoll) => {
      res.status(200).send(newPoll);
    }
  ).catch(() => {
    res.status(400).send();
  });
});

Why This Works

MongoDB interprets poll.0.votes as "access the first element (index 0) in the poll array, then increment its votes field". This matches the structure of your Schema, so the update will modify the correct value.

Bonus: Dynamic Array Element Updates

If you ever need to increment a vote for a specific poll option without hardcoding the index, you can use MongoDB's positional $ operator. For example, if you're filtering by an option's value, your query might look like:

Poll_Schema_Model.findOneAndUpdate(
  { "_id": '5b070f512a28d70eb0abaa51', "poll.option1": "FIRST OPTIONNN" },
  { $inc: { "poll.$.votes": userVote } },
  { new: true }
);

The $ here refers to the first array element that matches the filter criteria.

内容的提问来源于stack exchange,提问作者ANUBIS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:14:45