【问题标题】:Meteor update a Collection objectMeteor 更新一个 Collection 对象
【发布时间】:2015-06-20 11:24:56
【问题描述】:

在 Meteor 中,我有一个带有 Schema 的集合,并且动态添加了许多项目。

在这种情况下,我正在处理里程碑对象,一旦用户勾选了一项,我想将这个 Collections 项目中的完成更新为 true(默认为 false)

这是我的架构

milestones: {
type: Array,
optional: true
},
'milestones.$': {
type: Object
},
'milestones.$.name': {
type: String
},
'milestones.$.hours': {
type: Number
},
'milestones.$.complete': {
type: Boolean
}

我如何为此编写$set 声明?

【问题讨论】:

  • Milestones.update({_id:this._id},{$set:{'milestone.complete':true}}) 假设您正在使用事件处理程序并且可以使用 this._id 上下文。
  • 只有 Milestones 不是一个集合,它是 Projects 集合中的一个对象。我正在尝试这个Projects.update({_id:currentPostId, 'milestones.name':this.name}, {$set:{completed:true}}); 但无济于事..
  • 为什么需要这个名字?只需做一个Projects.update({_id:currentPostId},{$set:{'milestones.complete':true}})
  • 我需要确定里程碑,因为同一个对象中有多个。
  • Projects.update({_id:this._id},milestones:{$elemMatch:{'milestones.name':this.name}}, {$set: {'milestones.$.complete':true}}); 试试看

标签: meteor


【解决方案1】:

根据您的架构,您有一个包含对象数组的对象。所以你应该这样写$set

{$set: {'milestone.$.complete':value}}

这将更新与查询对应的第一个数组元素。

如果您想了解更多有关 Mongo 中数组更新的信息,可以找到 here 官方文档。

【讨论】:

    【解决方案2】:

    你有一个对象数组,所以$elemMatch 在这里解决问题。

    Projects.update({_id:this._id},{milestones:{$elemMatch:{'milestones.$‌​.name':this.name}},{$set:{'milestone.$.complete':value}}})
    

    【讨论】:

      【解决方案3】:

      感谢 Aldeed,我找到了一个解决方案 - 需要在服务器端调用它,否则它不会让更新发生。做:

      Projects.update({_id:currentPostId, 'milestones.name':name}, {$set:{'milestones.$.complete':true}});
      

      在客户端使用 Meteor.call 调用该函数,并带有所有需要的参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-07
        • 2018-10-15
        • 1970-01-01
        相关资源
        最近更新 更多