首页 > 解决方案 > 如何将对象推送到 Mongoose 对象子数组

问题描述

const CampaignSchema = new Schema(
  {
    name: {
      type: String,
      required: true
    },
    userId: {
      type: ObjectId,
      ref: 'User'
    },
    liEmail: {
      type: String,
      required: true
    },
    type: {
      type: String,
      enum: campaignConstants.COMPAIGN_TYPES,
      default: campaignConstants.CUSTOM
    },
    sequences: [
      {
        type: Sequence,
        required: true
      }
    ],
    excludeOption: {
      type: Boolean,
      default: false
    },
    sourceLinks: [String],
    data: [
      {
        targetId: {
          type: ObjectId,
          ref: 'Target'
        },
        profileLink: String,
        name: String,
        headline: String,
        imageurl: String,
        actions: [Activity]
      }
    ],
    browserKey: String
  },
  {
    versionKey: false,
    timestamps: true
  }
)

我要将ACTIVITY对象推送到campaign->data->actions。这个ACTIVITY对象将通过带有 browserKey 的请求来。此browserKeyprofielLink用于指示Campaign。和 profileLink 指示数据数组的特定对象

我自己试过这样但没有工作

const campaign = await Campaign.findOne({ browserKey })
const data = campaign.data.filter(
   e => e.profileLink === target.profileLink
)
data.actions.push(action)
await campaign.save()

标签: node.jsmongoose

解决方案


推荐阅读