Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
mongodb agrega dos colecciones y agrega nuevos campos

Tengo dos colecciones: autores y libros .

ejemplo de autor:

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

ejemplo de libro:

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

Quiero obtener la lista de libros con su nombre y apellido del autor.

Aquí está mi código actual:

 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; });

¡Esta no es una buena práctica porque para cada libro ejecuto otra solicitud a la base de datos mongodb! ¿Alguna solución mejor?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Versión mangosta para unir dos modelos con relación

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

Uso de agregación

 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 Report

0

Código limpio y mayor rendimiento con 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!