【发布时间】:2015-08-04 17:43:05
【问题描述】:
{ _id: 55c02ab7684c7a601ca24898,
title: 'this is a better poll',
link: 'this-is-a-better-poll',
creator: 'user',
__v: 0,
choices:
[ { text: 'Option 1', votes: 0 },
{ text: 'Option 2', votes: 0 } ] }
这是一个投票的例子。假设我的数据库中有多个。
我需要通过比较 Option 来更新客户端每次 POST 请求的 投票数发布到服务器并与数据库进行比较。
由于数据库中有多个轮询,我使用 链接 来查找确切的数据库对象。
我尝试了多种方法来更新投票数,但似乎没有任何效果,但更改标题却完美无缺。为什么?
失败的方法:
for example selection is:
var selection = 'Option 1';
var link = 'this-is-a-better-poll';
1) Model.where({"choices.text": selection}).update({$set: {"choices.votes" : 1}});
2) Model.update({"choices.text": selection}, {'$set': {"choices.$.votes" : 1}});
3) Model.findOne({
link: link
}, function(err, found) {
if (err) {
return res.status(400).send({
message: 'Error'
});
}
if (found) {
console.log(found.choices);
var arr = found.choices;
for (var i = 0; i < arr.length; i++) {
if (arr[i].text == selection) {
arr[i].votes = 1
console.log(arr[i].votes = 1);
}
found.save(function(err) {
if (err) res.send(err);
res.status(200).send({
message: 'Succes'
});
});
}
}
});
我该如何解决这个问题?进行选择时如何更新投票计数?
【问题讨论】:
标签: node.js mongodb mongoose mongodb-query