1

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

2
  • It would be very helpful if you could add extra bits in your question like your schema design, some sample documents and your expected JSON result example. Commented Jan 26, 2017 at 13:58
  • Apart from the fact that for loop is synchronous and it's iterating an asynchronous call (objModel.find(...)) you are bound to get incorrect results. Commented Jan 26, 2017 at 14:00

1 Answer 1

1

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 })
    })
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.