猫鼬不为子文档生成_id

发布时间:2020-07-07 14:16

我有一个简单的模式,里面有一个数组。当我创建一个包含映射数组中项目的新项目时,映射数组中的项目会自动分配一个_id。但是,当我尝试将项目添加到现有项目的映射数组时,将使用_id为null的新映射。如何获得猫鼬为我生成此_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 }
    );

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

回答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]
}