更新mongodb中的对象数组 [英] Updating array of objects in mongodb

查看:216
本文介绍了更新mongodb中的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新我的简单架构中的对象数组.当前,它将删除数据库中的所有内容并留下:

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

"careerHistoryPositions": []

我的简单模式如下:

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表单数据如下:

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

我的更新功能:

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

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

推荐答案

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

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

这篇关于更新mongodb中的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆