正在更新 mongodb 中的对象数组

Updating array of objects in mongodb

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

"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
      }
      }
    );
  }

我设法通过映射我的对象和 运行 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
    }
  }
})