【问题标题】:Mongoose $addToSet for array if item is unique如果项目是唯一的,则为数组添加 Mongoose $addToSet
【发布时间】:2021-08-27 22:46:24
【问题描述】:

目前,无论item.name 是否唯一,我的代码只是将任何新的flagDtos 添加到$addToSet,但我想更改它以便:

  • 如果item.name是唯一的,添加新的flagDtos对象
  • 如果与 item.name 匹配,则更新 flagDto

如何根据条件创建 $addToSet?

  async addFlagsToFeature(_id: number, flagDtos: FlagDto[]): Promise<FeatureResponse> {
    const filter: FilterQuery<FeatureDocument> = { _id };
    let success;
    var flagIds = [];

    return this.featureModel
      .findOneAndUpdate({ filter, $addToSet: { flags: flagDtos } })
      .then((doc) => {
        const featureDto = new FeatureDto();
        featureDto.mapFromSchema(doc);

        featureDto.flags.forEach((item) => {
          flagIds.push(new FlagDto({ featureFlagId: item.featureFlagId }));
          success = new SuccessFeatureResponseDto(featureDto.id, flagIds);
        });
        return new FeatureResponse(success, null);
      })
  }

这是我的FlagDto 课程

export class FlagDto {
  featureFlagId?: string;
  name: string;
}

【问题讨论】:

    标签: typescript mongodb mongoose


    【解决方案1】:

    $addToSet 最适合使用标量。在您的情况下,您将需要运行 2 个查询:

    如果不存在则插入子文档 ($push) ($nin):

    db.collection.update({
      <  your filter here  >
      "flags.name": {
        $nin: [
          < the name from FlagDto >
        ]
      }
    },
    {
      "$push": {
        "flags": < the FlagDto >
      }
    })
    

    更新($set)存在的那些(包括在前一个查询中插入的)

    db.collection.update({
      "flags.name": < the name from FlagDto >
    },
    {
      "$set": {
        "flags.$": < the FlagDto >
      }
    })
    

    依次运行两个查询(等待 $push 解析)或将它们打包在一个有序的批量写入中,这应该会快一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 2011-12-18
      • 1970-01-01
      • 2014-04-28
      相关资源
      最近更新 更多