$inc对MongoDB文档无作用,投票计数更新失败求助
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

