【问题标题】:Updating array of objects in mongodb更新 mongodb 中的对象数组
【发布时间】:2017-11-23 16:52:34
【问题描述】:

我正在尝试更新我的简单模式中的一组对象。目前,它会删除数据库中的所有内容并留下:

"careerHistoryPositions": []

我的simple-schema 看起来像:

const ProfileCandidateSchema = new SimpleSchema({
      userId: {
        type: String,
        regEx: SimpleSchema.RegEx.Id
      },
      careerHistoryPositions: { type: Array, optional: true },
      'careerHistoryPositions.$': { type: Object, optional: true },
      'careerHistoryPositions.$.uniqueId': { type: String, optional: true },
      'careerHistoryPositions.$.company': { type: String, optional: true },
      'careerHistoryPositions.$.title': { type: String, optional: true }
    });

如果 console.log 表单数据如下所示:

 careerHistoryPositions:  [Object, Object],
    0: Object
    company: "Test company"
    title: "Test Title"
    uniqueId: 1498004350350
    1: Object
    company: "Test company 2"
    title: "Test Title 2"
    uniqueId: 149800433221

我的更新功能:

handleFormSubmit(event) {
    event.preventDefault();
    const { careerHistoryPositions } = this.state;

    ProfileCandidate.update({ _id: this.state.profileCandidateCollectionId },
      { $set: {
        careerHistoryPositions
      }
      }
    );
  }

【问题讨论】:

  • 您的架构在字段名称中有$?我认为不会。如果它“真的”如您所定义的那样,那么您做的就是错误$ 在此上下文中为positional $ operator. 保留。我认为你需要展示你已经实现的实际代码的完整背景,因为你要么歪曲了,要么误解了这一切是如何工作的。
  • 我已经更新了完整的模式,它基于 simple-schema 包(见链接)。我很高兴提供更多代码,但我不确定我还能提供什么。请指教。
  • 我不喜欢 SimpleSchema 的处理方式,因为它不像“MongoDB”。 Combining Schemas 演示了定义模式的更好方法。因此,您还应该遵循位置 $ 运算符的官方文档(已提供链接)进行实际更新。如果您想$set 匹配元素,您还需要指定"uniqueId" 或匹配.update() 的“查询”部分中的数组元素的内容。所有内容都包含在文档链接中。
  • 谢谢,@Neil。还在学习。您的参考资料很棒,但它们是错误的文档。我正在使用 Simple-Schema V2 - github.com/aldeed/node-simple-schema
  • 我知道。我在评论中链接到 SimpleSchema 文档中的“组合模式”。您应该单击这些链接并阅读它们。我现在太忙了,没时间研究这个,所以你应该在现在和如果/当有人给你答案之间这样做。

标签: mongodb reactjs meteor simple-schema meteor-collection2


【解决方案1】:

我设法通过映射我的对象并运行 2 个单独的更新来解决此问题。第一个删除旧元素,第二个添加更新版本。我确信有更好的方法可以做到这一点,但是,这似乎确实有效。

handleFormSubmit(event) {
  event.preventDefault();
  const { careerHistoryPositions } = this.state;

  ProfileCandidate.update({_id: this.state.profileCandidateCollectionId}, { $unset: {
    'careerHistoryPositions': {}
  }
})        


const updatePosition = this.state.careerHistoryPositions.map((position) => {
  ProfileCandidate.update({_id: this.state.profileCandidateCollectionId}, { $push: {
    'careerHistoryPositions': {
      company: position.company,
      title: position.title,
      uniqueId: position.uniqueId
    }
  }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    相关资源
    最近更新 更多