Updating array of objects in mongodb

独自空忆成欢 提交于 2019-12-20 06:37:20

问题


I'm trying to update an array of objects in my simple-schema. Currently, it removes everything in the database and leaves behind:

"careerHistoryPositions": []

My simple-schema looks like:

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

If console.log form data looks like:

 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

My update function:

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

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

回答1:


I managed to fix this by mapping over my object and running 2 separate updates. The first removes the old element and the second adds the updated version. I'm sure there is a better way to do this, however, this does seem to work.

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


来源:https://stackoverflow.com/questions/44665009/updating-array-of-objects-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!