javascript - Mongoose 查找,然后填充,然后重命名子文档

如何在列表中填充索引,然后重命名其中一个索引?假设我有以下架构

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

我的收据是这样填充的

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("..."),
}

我希望它用 nameaddress 填充 supplier_id。然后将 supplier_id 重命名为 supplier

回答1

将聚合与 $lookup 一起使用

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