Home > Net >  Reference to an object inside an array in another collection
Reference to an object inside an array in another collection

Time:01-28

Following is the WorkingDay model

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);

And the following is the 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);

Every object inside the availableSlots array has it own unique _id.WorkingDay document sample

How to create a reference to an object inside availableSlots from the assignedSlot field of response? Also how to populate the same?

I tried referencing the availableSlots objects using

assignedSlot: { type: Schema.Types.ObjectId, ref: availableSlots, default: null }

and

assignedSlot: { type: Schema.Types.ObjectId, ref: "WorkingDay.availableSlots", default: null }

but it did not work.

CodePudding user response:

const { ObjectId } = mongoose.Schema.Types;

assignedSlot: [{ type: ObjectId ,ref:"WorkingDay"}]

CodePudding user response:

Given your schema structure, you should reference the WorkingDay collection:

assignedSlot: { type: Schema.Types.ObjectId, ref: 'WorkingDay', default: null }

Then, you can populate the reference with:

const response = await Response.findOne({}).populate('assignedSlot').exec();
if (response && response.assignedSlot) {
    console.log(response.assignedSlot.availableSlots);
}
  • Related