Mongoose not generating _id for subdocument
我有一个简单的模式,里面有一个数组。当我创建一个包含映射数组中的项目的新项目时,映射数组中的项目会自动分配一个_id。但是,当我尝试将项目添加到现有项目的映射数组时,将使用_id
我的架构是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | { 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 } ); |
我尝试了两种方法将项目添加到
选项1:
1 2 | let item = await Mappings.findOne({ _id: id }); return await item.mapping.create(mapping); |
选项2:
1 2 3 4 5 | return await Mappings.update( { _id: id }, { $push: { mapping } }, { upsert: true } ); |
如何让猫鼬为映射数组中的项生成_id?
尝试在用户架构文件中将映射定义为架构。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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, } }) |
然后您的主架构变为
1 2 3 4 5 6 7 8 | { email: { type: String, required: true, index: true }, mappings: [mappingSchema] } |