Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda