我目前正在使用MEAN堆栈,并且我正在尝试更新嵌入式文档。一切似乎都在执行,但刷新后数据不会持续:
// Soon to be update answer
exports.updateAnswer = function(req, res) {
var ansId = req.params.aid;
var result;
Poll.findById(req.params.id,function(err, poll){
if(err) { return handleError(res, err); }
poll.answers.forEach(function(answer){
if(ansId == answer._id) result = answer;
})
var updated = _.merge(result, req.body);
poll.markModified('answers');
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, poll);
});
});
};
我的架构:
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var AnswerSchema = new Schema({
answer: String,
votes:{type: Number, default: 0}
});
module.exports = mongoose.model('Answer', AnswerSchema);
var PollSchema = new Schema({
author: String,
question: String,
answers: [AnswerSchema]
});
module.exports = mongoose.model('Poll', PollSchema);
提出请求:
$scope.vote = function(answer) {
$scope.pollObj.answers.forEach(function(el,indx){
if(el['_id'] == $scope.radioVal.selected) {
el['votes']++;
$http.put('/api/polls/'+$scope.pollId+'/answers/'+el['_id'],el).
success(function(data){
console.log(data);
})
}
})
答案 0 :(得分:0)
laggingreflex提供的答案:
exports.updateAnswer = function(req, res) {
var ansId = req.params.aid;
var result;
Poll.findById(req.params.id,function(err, poll){
if(err) { return handleError(res, err); }
poll.answers.forEach(function(answer){
if(ansId == answer._id) result = answer;
})
var updated = _.merge(result, req.body);
poll.markModified('answers');
poll.save(function (err) { // <== change here
if (err) { return handleError(res, err); }
return res.json(200, poll);
});
});
};