[英]Reference to an object inside an array in another collection
以下是工作日WorkingDay
const workingDaySchema = new mongoose.Schema({
date: { type: String, unique: true, required: true },
availableSlots: [
{
startTime: Date,
endTime: Date,
size: Number,
enrolledUsers: [{ type: Schema.Types.ObjectId, ref: 'Response' }]
}
]
})
module.exports = mongoose.model('WorkingDay', workingDaySchema);
以下是Response
model:
const responseSchema = new Schema(
{
id: { type: String },
name: { type: String, required: true },
age: { type: String },
gender: { type: String },
height: { type: String },
weight: { type: String },
food: { type: String },
phone: { type: String },
email: { type: String },
category: { type: Array },
answers: { type: Object },
assignedSlot: { type: Schema.Types.ObjectId, ref: availableSlots, default: null }
},
{
timestamps: true,
}
);
module.exports = mongoose.model("Response", responseSchema);
availableSlots
数组中的每个 object 都有自己唯一的 _id。
如何从response
的assignedSlot
字段创建对availableSlots
内 object 的引用? 还如何填充相同的?
我尝试使用引用 availableSlots 对象
assignedSlot: { type: Schema.Types.ObjectId, ref: availableSlots, default: null }
和
assignedSlot: { type: Schema.Types.ObjectId, ref: "WorkingDay.availableSlots", default: null }
但它没有用。
const { ObjectId } = mongoose.Schema.Types;
assignedSlot: [{ type: ObjectId ,ref:"WorkingDay"}]
鉴于您的架构结构,您应该引用WorkingDay
集合:
assignedSlot: { type: Schema.Types.ObjectId, ref: 'WorkingDay', default: null }
然后,您可以使用以下内容填充参考:
const response = await Response.findOne({}).populate('assignedSlot').exec();
if (response && response.assignedSlot) {
console.log(response.assignedSlot.availableSlots);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.