Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Add a subdocument in array element

Below function returns an array in 'results' argument:

module.exports.get = function (req, res) {
    objModel.find(function (err, results) {
        res.json({ record: results })
    })
};

I want to add its reference collection record list in one new object for each element. Just like the following:

for (var i = 0; i < results.length; i++) {
    module.exports.get = function (req, res) {
        objModel.find({ _id: results[i]._id }, function (err, record) {
            results[i]["objNew"] = record
        })
    };
}

My full code looks like:

module.exports.get = function (req, res) {
    objModel.find(function (err, results) {
        for (var i = 0; i < results.length; i++) {
            module.exports.get = function (req, res) {
                objModel.find({ _id: results[i]._id }, function (err, record) {
                    results[i]["objNew"] = record
                })
            };
        }
        res.json({ recordList: results })
    })
};

It return error: "objNew" is unknown.

I display output record json list in this link: Plunker

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I believe you are after the $lookup operator in the aggregation framework which will give you the desired result. Consider running the following aggregate operation:

module.exports.get = function (req, res) {
    objModel.aggregate([
        {
            "$lookup": {
                "from": "objModelcollectionName", /* "self-join" with collection */
                "localField": "_id",
                "foreignField": "_id",
                "as": "objNew"
            }
        }
    ]).exec(function (err, results) {
        if (err) throw err;
        res.json({ recordList: results })
    })
};
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!