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

146
Visualizações
Map the nested data from other table using promise and async-await

I need the expert advice for this code. I need to know Is there any better way to solve this.

I am using the mongoose for db. I have a dataset like this:

Below is matchTable:

{
  _id: 617bc0113176d717f4ddd6ce,
  car: [],
  status: true
},
{
  _id: 617bc0113176d717f4ddd6cg,
  car: [
    {
      aid: '5c1b4ffd18e2d84b7d6febcg',
    }
  ],
  status: true
}

And I have a Car table in which car name is there on behalf of id like this

{ _id: ObjectId('5c1b4ffd18e2d84b7d6febce'), name: 'ford' },
{ _id: ObjectId('5c1b4ffd18e2d84b7d6febcg'), name: 'mitsubishi' },

So I want to make join the data from car table, so that response get name on behalf of aid. Desired result will be like

{
  _id: 617bc0113176d717f4ddd6ce,
  car: [],
  status: true
},
{
  _id: 617bc0113176d717f4ddd6cg,
  car: [
    {
      aid: '5c1b4ffd18e2d84b7d6febcg',
      name: 'mitsubishi'
    }
  ],
  status: true
}

For that I have to merge the car table on matchTable. I have done this but I want to give some suggestion that is there any better way to do or is it fine. I need expert advice.

const getData = await matchTable.find(
  { status: true }
).lean().exec();
let dataHolder = [];
await Promise.all (
  getData.map(async x => {
    await Promise.all(
      x.car.map(async y => {
        let data = await Car.findOne(
          { _id: ObjectId(y.aid) },
          { name: 1 }
        ).lean().exec();
        y.name = '';
        if (data) {
          y.name = data.name;
        }
      })
    )
    // If I return { ...x }, then on response it will return {}, {} on car column
    dataHolder.push(x) //So I have chosen this approach
  })
);

Please guide me if any better and efficient solution is there. Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can make use of aggregation here.

const pipeline = [
    {
        $match : { status : true }  
    },
    {
        $unwind: '$matchtable',
    },
    {
        $lookup: {
            from: "cars",
            localField: "car.aid",
            foreignField: "_id",
            as: "matchcars"
        }
    },
    {
        $addFields: {
          "car.carName": { $arrayElemAt: ["$matchcars.name", 0] }
        }
    },
    {
        $group: {
            _id: "$_id",
            cars: { $push: "$matchcars" }
        }
    }
]

const result = await matchTable.aggregate(pipeline).exec();

Please make sure, aid field inside car array (in matchTable collection) is an ObjectId because its being matched to _id (which is an ObjectId) inside cars collection.

about 4 years ago · Juan Pablo Isaza 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