在数组元素中添加一个子文档

下面的函数返回“结果”参数中的一个数组:

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

我想将其引用集合logging列表添加到每个元素的一个新对象中。 就像下面这样:

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

我的完整代码如下所示:

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

它返回错误:“objNew”是未知的。

我在这个链接显示输出loggingjson列表: Plunker

我相信你在聚合框架中的$lookup操作符之后会给你想要的结果。 考虑运行以下集合操作:

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