【问题标题】:Meteor.methods() unexpected behaviour when using $push and db.update [closed]使用 $push 和 db.update 时的 Meteor.methods() 意外行为 [关闭]
【发布时间】:2013-01-06 21:57:46
【问题描述】:

我有这个代码来更新一个条目:

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...]。

有人知道为什么吗?

【问题讨论】:

  • 如果你想+1,为什么要+50?
  • 这是我代码中其他地方的错误。对不起各位,谢谢你们的回答

标签: javascript node.js mongodb meteor


【解决方案1】:

让我们先创建 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]

【讨论】:

  • 抱歉,打错了。忘记第二次更新。而“加 1”的增量只是一个例子。我真正想要的是一个“加5”的增量
  • 我编辑了帖子以使其更加连贯
  • 我可以看到数字在增加,但随后又恢复了......
  • 嗯,我不确定是不是诚实的。您确定您正在获取/更新正确的项目文档吗?或者,您的应用程序中可能还有其他代码可以重置您的列表。
  • 是的,我确定。这一定是我不知道的 update() 或 methods() 甚至 Meteor.call() 的一个技巧..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 2015-02-18
  • 2013-03-12
  • 1970-01-01
相关资源
最近更新 更多