【问题标题】:meteor collection.update is not updating documentmeteor collection.update 不更新文档
【发布时间】:2015-04-05 18:44:32
【问题描述】:

我正在尝试在客户端方法中触发更新(考虑稍后移入服务器),如下所示:

 Meteor.methods({
    // Calling this and passing in a currentSelected value = "avatar" on click
    'updateSelectedDocument' : function(currentSelected) {
      var current = LayoutVariations.findOne({elementID: currentSelected});
      var index = current.currentIndex;
      myCollection.update({_id :current._id}, {currentIndex: 2});
    }
 });

.update 应该找到文档并更新该文档的 currentIndex 属性,该属性是一个整数。

我通过传入_id(例如“GRvujvgBEmem3Dp3d”)在控制台中运行myCollection.update({_id :current._id}, {currentIndex: 2});,它可以工作。当我在方法中调用它时,它只是没有更新,也没有抛出任何错误。

想知道可能是什么问题。

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    在更新中使用$set 运算符将currentIndex 字段的值替换为指定的:

    Meteor.methods({
         // Calling this and passing in a currentSelected value = "avatar" on click
         'updateSelectedDocument' : function(currentSelected) {
          var current = LayoutVariations.findOne({elementID: currentSelected});
          var index = current.currentIndex;
          myCollection.update({_id :current._id}, {$set: { currentIndex: 2 } }, function(error, affectedDocs) {
              if (error) {
                  throw new Meteor.Error(500, error.message);
              } else {
                  return "Update Successful";
              }
          });
        }
     });
    

    【讨论】:

    • 感谢您的回答。我尝试了$set 运算符。但是我看到了同样的行为。运行 myCollection.update({_id :current._id}, {$set: { currentIndex: 2 } });(使用实际 _id)返回 1 并更新文档。但是从函数内部更新它似乎不会更新数据库中的文档。
    • 你在哪里调用客户端的方法Meteor.call("updateSelectedDocument", function(error, result){...});
    • 就在模板点击事件中``Template.frame.events({ 'click button': function () { Meteor.call('updateSelectedDocument', currentSelected); } });`` I只是将方法移到服务器中(“服务器”文件夹下的文件)。它似乎正在正确更新。看起来 CRUD 方法只在服务器端有效?
    • 来自 Andrew Scala 的introductory tutorial 的一般建议,他声称当你想更新和修改你的数据库文档时,应该在服务器上使用 Meteor.methods():这个想法是您在服务器上定义所有执行危险操作(如修改和更新数据)的函数,然后让客户端调用这些函数并像常规函数一样获取返回值。客户永远不会看到实现,也不会亲自修改数据。服务器完成所有工作。
    • 我认为这很有意义。因此,即使在开发模式下,这些更新方法也不会在客户端工作。我会记住的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多