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

158
Visualizações
mongodb aggregate two collections and add new fields

I have two collections: authors and books

author example:

{
   _id: "605f6746c114544ee04228bd"
   firstName: "firstName",
   lastName: "lastName",
}

book example:

{
   _id: "605f6746c114544ee04228bd"
   title: "title",
   pages: 350,
}

I want to get the list of books with thier author firstName and lastName.

here is my current code:

let books;

books = await Book.find();
books.forEach(async (book, i) => {
  const author = await Author.findOne(
    { _id: book.authorId },
    { firstName: 1, lastName: 1, _id: 0 }
  );
  books[i].authorFirstName = author.firstName;
  books[i].authorLastName = author.lastName;
});

This is not a good practice because for each book I execut another request to mongodb database! Any better solution?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Mongoose version to join two models with relationship

books = await Book.find({}).populate({ path:"authorId", select:{firstName:1, lastName:1}})

Using aggregation

let books = await Book.aggregation([
   { 
     $lookup:{
        from:"collection_of_author",
        localField: "authorId",
        foreignField: "_id",
        as: "author"
     }
   },
  {
    $unwind: {
       path:"authorId",
       preserveNullAndEmptyArrays:true 
    }
  }])
over 4 years ago · Santiago Trujillo Relatório

0

Clean code and higher performance using mongoose populate

  import Book from "../models/Book";
  import Author from "../models/Author";

  let books = await Book.find().populate({
    path: "authorId",
    model: Author,
    select: { firstName: 1, lastName: 1, _id: 0 },
  });
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