简体   繁体   English

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

[英]Mongoose find, then populate, then rename subdocument

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 .我希望它用nameaddress填充supplier_id ID。 And then rename the supplier_id to supplier .然后将供应商 ID 重命名为supplier_id supplier

use aggregate with $lookup将聚合与 $lookup 一起使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM