I am making a simple full-stack javascript polls app using Yeoman's angular-fullstack generator. I have got to the point where I need to log user input to register a vote on an individual poll's answer.
Currently, my code affects the client-side code correctly, but doesn't update the database.
Here is the schema:
var PollSchema = new Schema({
creator: String,
title: String,
answers: [{
value: String,
votes: Number
}]
});
Here is the controller:
'use strict';
angular.module('angFullstackCssApp')
.controller('ViewCtrl', function ($scope, $routeParams, $http) {
$http.get('/api/polls/' + $routeParams._id).success(function (poll) {
console.log(poll);
$scope.poll = poll;
$scope.radioData = {
index: 0
};
$scope.submitForm = function () {
console.log($scope.radioData.index);
$scope.poll.answers[$scope.radioData.index].votes += 1;
// Change database entry here
$http.put('/api/polls/' + $routeParams._id, {answers: $scope.poll.answers});
};
});
});
and here is the View:
<form ng-submit="submitForm()">
<div ng-repeat="answer in poll.answers">
<label><input type="radio" name="option" ng-model="radioData.index" value="{{$index}}"/>
{{ answer.value }} - {{ answer.votes }} Votes
</label>
</div>
<button class="btn btn-success" type="submit">Vote!</button>
</form>
In my terminal, I am getting a successful put request according to the ID I am passing in...
PUT /api/polls/56229ba4e10ae6ad29b7a493 200 3ms - 225b
...but nothing changes in my database. I get no console errors.
Here is my route:
router.put('/:id', controller.update);
and the update
function (part of the yeoman default):
// Updates an existing poll in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Poll.findById(req.params.id, function (err, poll) {
if (err) { return handleError(res, err); }
if(!poll) { return res.status(404).send('Not Found'); }
var updated = _.merge(poll, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.status(200).json(poll);
});
});
};
Edit: I've realised what's going on when a vote is submitted. When user clicks vote, a PUT request goes through to the server, and updates the value:
However, when the page is refreshed, it shows what has actually happened; all the values in the database have changed to the first answer value:
Still no console errors. If a value is selected and voted that isn't the first value, all the values change to the first regardless, but no votes are registered.
- How can I write a PUT request that successfully updates my database?