簡體   English   中英

在另一個集合中的數組中引用 object

[英]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。 工作日文件樣本

如何從responseassignedSlot字段創建對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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM