'Mongoose query to populate list values

How do I populate an index inside of a list? Say I have the following schema's

const supplierSchema = new mongoose.Schema({
    name: String,
    address: String,
    size: Number,
    ... (19 other fields)
    supplier_id: mongoose.Schema.Types.ObjectId,
});

const itemsSchema = new mongoose.Schema({
    name: String,
    date_time: {type: Date, default: Date.now},
    supplier_id: mongoose.Schema.Types.ObjectId,
    item_id: mongoose.Schema.Types.ObjectId,
});                                                                                                                                                                                                     
                                                                                                                                                                                                                                                                                                                                                                                 
const receiptSchema = new mongoose.Schema({
    date_time: {type: Date, default: Date.now},
    items: [itemSchema]
    receipt_id: mongoose.Schema.Types.ObjectId,
});
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
const Receipt = mongoose.model('Photo', photoSchema);

My Receipt is populated such that

Receipt.findById(<insertID>) currently gives:
{
    receipt_id: ObjectId("..."),
    date_time: ISODate("..."),
    items: [
      {
        name: "...",
        date_time: ISODate("..."),
        supplier_id: ObjectId("..."),
        item_id: ObjectId("...")
      },
      {
        name: "...",
        date_time: ISODate("..."),
        supplier_id: ObjectId("..."),
        item_id: ObjectId("...")
      }
    ],
  receipt_id: ObjectId("..."),
}

I would like for it to populate the supplier ID with name and address.



Solution 1:[1]

You can populate across multiple levels using populate:

Receipt
    .findById(<insertID>)
    .populate({
        path: 'items',
        populate: { path: 'supplier_id' }
    })
    .exec()

For more information see the official docs

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lpizzinidev