【发布时间】: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?
【问题讨论】: