Home > Software design >  Mongoose find, then populate, then rename subdocument
Mongoose find, then populate, then rename subdocument

Time:05-26

How do I populate an index inside of a list and afterwards rename one of the indexes? Say I have the following schema's

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

const itemsSchema = new mongoose.Schema({
    name: String,
    supplier_id: mongoose.Schema.Types.ObjectId,
    item_id: mongoose.Schema.Types.ObjectId,
});                                                                                                                                                                                                     
                                                                                                                                                                                                                                                                                                                                                                                 
const receiptSchema = new mongoose.Schema({
    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("..."),
    items: [
      {
        name: "...",
        supplier_id: ObjectId("..."),
        item_id: ObjectId("...")
      },
      {
        name: "...",
        supplier_id: ObjectId("..."),
        item_id: ObjectId("...")
      }
    ],
  receipt_id: ObjectId("..."),
}

I would like for it to populate the supplier_id with name and address. And then rename the supplier_id to supplier.

CodePudding user response:

use aggregate with $lookup

Receipt.aggregate([
  {$match  : {_id : <insertID>} },
  {
    $lookup : {
      from: 'supplier',
      localField: 'items.supplier_id',
      foreignField: '_id',
      as: 'supplier'
    }
  },
  {
    $unwind : {
      path : "supplier"
    }
  }
])
  • Related