我有以下数据结构:
const schema = new Schema({
userId: { type: String, required: true },
image: { type: String, required: true},
name: { type: String, required: true },
description: { type: String, required: true },
subCategories: [{ type: mongoose.Schema.Types.ObjectId, ref: 'SubCategories' }]
}, {
strict: 'throw'
});
export const Plan = mongoose.model('Plan', schema);
const schema = new Schema({
userId: { type: String, required: true },
name: { type: String, required: true },
description: { type: String, required: true }
}, {
strict: 'throw'
});
export const SubCategories = mongoose.model('SubCategories', schema);
我希望每次创建新的Plan
实体时,将每个子类别保存在单独的集合中。
这要求我迭代子类别并创建每个子类别。
例如:
plan.subCategories = await Promise.all(plan.subCategories.map(async (s: IWorkoutDay) => {
const sub = new SubCategories(s);
sub.userId = userId;
await sub.save();
return sub;
}));
const p = new Plan(plan);
p.userId = userId;
await p.save();
并且每次我想编辑我需要迭代的元素的子类别时找到元素并分别更新每个元素。 有没有更简单的方法来实现这一目标?因为这对我来说似乎很复杂。