Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda