简体   繁体   English

对作为数组一部分的 object 的聚合查找

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

I'm trying with the code below to populate the contact field by getting data from collection companies.contacts .我正在尝试使用下面的代码通过从 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);
};

By using the code from above, I can get populate company, but I cannot populate custRFQ.contact and custQUO.contact .通过使用上面的代码,我可以获得填充公司,但我无法填充custRFQ.contactcustQUO.contact

Please help me with some advice.请帮我一些建议。 Thanks in advance!提前致谢!

Update:更新:

Response is:回应是:

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

The contact defined under the indicated order exist.指定顺序下定义的联系人存在。 Now I realized that probably I need to match the company also under lookup.现在我意识到,可能我还需要匹配正在查找的公司。

You forgot new keyword at objectOrderTab = mongoose.Schema({您在new objectOrderTab = mongoose.Schema({

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

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