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

137
Visualizações
How to get the first item of an array field I get with populate in mongoose?

I have a mongodb collection and I want to populate a nested field when I return data from the database. I want to return only specific fields, the code below with explain more.

this is my schema

const hallSchema = new Schema({
  hallName: { type: String, required: true },
  email: { type: String, required: true },
  images: [{ type: String, required: true }],
});

and this is code I'm writing to get the first image of the images array 

chatRooms = await ChatRoom.find({ _id: convertedIds })
      .populate("hallId", `hallName ${images[0]}`);

the query above is failing because it is invalid, how can I get the first item of images array? Thanks for any help

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

0

What I understand is that you want to populate data in hallId and from populated hallId data you want to select the first image from the images array. So to project fields from populated data you can do this, It works for me,

const chatRooms = await ChatRoom.find({ _id: convertedIds })
    .populate({ path: 'hallId', select: {
        hallName: 1,
        images: { $slice: ['$images', 1] },
    }
});
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