【问题标题】:Mongoose not generating _id for subdocumentMongoose 不为子文档生成 _id
【发布时间】:2020-10-27 19:59:36
【问题描述】:

我有一个简单的架构,里面有一个数组。当我创建一个包含映射数组中的项目的新项目时,映射数组中的项目会自动分配一个_id。但是,当我尝试将项目添加到现有项目的映射数组时,会使用null 的_id 创建新映射。如何让猫鼬为我生成这个 _id?我在文档中的任何地方都找不到它。

我的架构是:

  {
    email: {
      type: String,
      required: true,
      index: true,
    },
    mapping: [
      {
        mapToField: {
          type: String,
          enum: [
            "subject",
            "location",
            "company",
            "hours",
            "rate",
            "startDate",
            "endDate",
          ],
          required: true,
        },
        mapToLabel: {
          type: String,
          required: true,
        },
        regex: {
          type: String,
          required: true,
        },
      },
    ],
  },
  { timestamps: true }
);

我尝试了两种将项目添加到 mapping 数组的方法,但是这两个选项都会导致在没有 _id 的情况下添加项目。

选项 1:

    let item = await Mappings.findOne({ _id: id });
    return await item.mapping.create(mapping);

选项 2:

    return await Mappings.update(
      { _id: id },
      { $push: { mapping } },
      { upsert: true }
    );

如何让 mongoose 为映射数组中的项目生成 _id?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    尝试将映射定义为用​​户架构文件中的架构。

    const mappingSchema = new mongoose.Schema({
            mapToField: {
              type: String,
              enum: [
                "subject",
                "location",
                "company",
                "hours",
                "rate",
                "startDate",
                "endDate",
              ],
              required: true,
            },
            mapToLabel: {
              type: String,
              required: true,
            },
            regex: {
              type: String,
              required: true,
            }
    })
    

    然后你的主架构就变成了

    {
      email: {
        type: String,
        required: true,
        index: true
      },
      mappings: [mappingSchema]
    }
    

    【讨论】:

    • 是的,我认为这是解决问题的最佳方法。 Mongo 仅在创建用户时为映射生成 _ids,因此单独的模式是最简单的。谢谢!
    猜你喜欢
    • 2018-06-25
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    相关资源
    最近更新 更多