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
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 })
})
};