I am currently working on a polls application using angular, express, and mongoose.
Here is an overview of my data structure:
var mongoose = require('mongoose');
var responseSchema = new mongoose.Schema({
responseText: String,
votes: {
type: Number,
default: 0
}
})
module.exports = mongoose.model('Responses', responseSchema);
var pollsSchema = new mongoose.Schema({
question: String,
responses: [responseSchema]
})
module.exports = mongoose.model('Polls', pollsSchema);`
Essentially, I have a model for polls which contains a subdocument model for responses.
When a user casts a vote, I aim to increment the vote count for that particular response. Here is the code snippet I am currently working on but encountering issues.
router.post('/api/polls/:id/vote', function (req, res, next) {
console.log("Poll ID : " + req.params.id);
console.log("Option ID : " + req.body._id);
Polls.findOneAndUpdate({
_id: req.params.id
}, {
$inc: {
'responses.id(req.body.id).votes': 1
}
}, function (err, post) {
if (err) return next(err);
console.log(err);
console.log(post);
console.log(post.responses.id(req.body._id).votes);
});
})
Update: Revised version
In summary, the request parameters include the Poll ID while the response body includes the response ID. Although I can log the vote value, I am struggling with writing the appropriate query. Any assistance would be greatly appreciated.
Thank you!