我有这个代码来更新条目:
function updateList(listTime) {
var firstList = Project.find().fetch()[0].list; // returns a list
var nextElement = (firstList[firstList.length-1] + 50); // value of last + 50
Project.update({name: "List 1"}, {$push: {list: nextElement}});
}
我从以下地方调用它:
Meteor.methods({
updateList: updateList,
});
因为我使用的是 python ddp 客户端并且需要这样。
问题是 nextElement 并没有真正增加我列表中的序列。想象一下,我的列表是 [50,100,150,...],如果我调用 updateList,它会变成 [50,100,150,150,150,150...] 等等...并且它应该变成 [50,100,150,200,250,300...]。
有人知道为什么吗?
最佳答案
让我们首先将 nextElement 设置为 +1
而不是 +50
。
var nextElement = (firstList[firstList.length-1] + 1);
请注意,listTime 将成为列表中的最后一个元素。因此,如果您运行 updateList(20)
,列表将变为 [1, 2, 3, 4, 5, 6, 7, 20]
。如果您随后调用 updateList(2)
,它将变为 [1, 2, 3, 4, 5, 6, 7, 20, 21, 2]
等等。
我不确定 listTime 应该做什么,但如果您希望将 last int + 1
添加到列表中:
function updateList() {
var firstList = Project.find().fetch()[0].list;
var nextElement = (firstList[firstList.length-1] + 1);
Project.update({name: "List 1"}, {$push: {list: nextElement}});
}
这将导致:
Project.find().fetch()[0].list
> [1, 2, 3, 4, 5, 6, 7]
updateList()
Project.find().fetch()[0].list
> [1, 2, 3, 4, 5, 6, 7, 8]
updateList()
Project.find().fetch()[0].list
> [1, 2, 3, 4, 5, 6, 7, 8, 9]
关于javascript - 使用 $push 和 db.update 时 Meteor.methods() 出现意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14187231/