[英]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.