简体   繁体   中英

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 .

// 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 .

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({

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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