簡體   English   中英

對作為數組一部分的 object 的聚合查找

[英]Aggregate lookup for an object which is part of an array

我正在嘗試使用下面的代碼通過從 collection companies.contacts獲取數據來填充聯系人字段。

// COMPANY MODEL

const objectContact = {
  name: { type: String, required: true },
  email: { type: String, required: true }
};

const schemaCompany = new mongoose.Schema({
  name: { type: String, required: true },
  contacts: { type: [objectContact], default: undefined }
});

// -----------------

// ORDER MODEL

const objectOrderTab = {
  contact: { type: mongoose.Schema.Types.ObjectId, ref: 'Company' },
};

const schemaOrder = new mongoose.Schema({
  orderNo: Number,
  orderDate: { type: Date, default: Date.now },
  company: { type: mongoose.Schema.Types.ObjectId, ref: 'Company', required: true },
  custRFQ: objectOrderTab,
  custQUO: objectOrderTab,
});

// -----------------

exports.getOrder = catchAsync(async (req, res, next) => {
  
  let order = await Order.aggregate([
    { $match: { orderNo: parseInt(req.params.order) } },
    { $lookup: { from: 'companies', localField: 'company', foreignField: '_id', as: 'company' } },
    { $lookup: { from: 'companies.contacts', localField: 'custRFQ.contact', foreignField: '_id', as: 'custRFQ.contact' } },
    { $lookup: { from: 'companies.contacts', localField: 'custQUO.contact', foreignField: '_id', as: 'custQUO.contact' } }
  ]);
 
  res.status(200).json(order);
};

通過使用上面的代碼,我可以獲得填充公司,但我無法填充custRFQ.contactcustQUO.contact

請幫我一些建議。 提前致謝!

更新:

回應是:

[
    {
        "_id": "5ff2fb1e6c8567171031c1a4",
        "orderNo": 1000,
        "company": [
          {
            "_id": "5fd2bdfa57c6291fe0f0628f",
            "name": "DELPHI",
            "contacts": [
                {
            
                    "_id": "5fd2c81175a80e3b54f191c5",
                    "name": "Some name",
                    "email": "xxx@delphi.com",
                }               
            ]
          }
        },
        "custRFQ": {
            "contact": [],
        },
        "custQUO": {
            "contact": [],
        }
    }
]

指定順序下定義的聯系人存在。 現在我意識到,可能我還需要匹配正在查找的公司。

您在new objectOrderTab = mongoose.Schema({

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM