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

242
Views
NodeJS y MongoDB: use agregado y $búsqueda junto con findById

Quiero hacer una relación entre dos colecciones: un libro y colecciones de autor. Si uso solo obtener y mostrar todos mis libros e integrar los datos sobre el autor por identificación, funciona.

Esquema del autor:

 const AuthorSchema = new mongoose.Schema({ name: { type: String, required: true }, surname: { type: String, required: true }, dateOfBirth: { type: String, required: true }, countryOfBirth: { type: String, required: true }, });

esquema del libro:

 const BookSchema = new mongoose.Schema({ owner: { type: String, required: true }, pagesNo: { type: String, required: true }, releaseDate: { type: String, required: true }, country: { type: String, required: true }, authorID: { type: Schema.Types.ObjectId, ref: "Author", required: true }, <-- HERE I NEED DATA ABOUT AUTHOR });

Mi función express que funciona para obtener todos los datos:

 router.get("/", async (req, res) => { try { let books = await Book.aggregate([ { $lookup: { from: "authors", localField: "authorID", foreignField: "_id", as: "author", }, }, ]); res.status(200).json(books); } catch (err) { res.status(404).json({ success: false, msg: "Book is not found" }); } });

Pero ahora quiero mostrar esos datos unidos también cuando busco un solo libro por ID (findById()). Obtuve un estado de error si uso una función como esta:

 router.get("/:bookId", async (req, res) => { try { let book= await Book.aggregate([ { $lookup: { from: "authors", localField: "authorID", foreignField: "_id", as: "author", }, }, ]); book= book.findById({ _id: req.params.bookId}); res.status(200).json(book); } catch (err) { res.status(404).json({ success: false, msg: "Book is not found" }); } });

Gracias por tu ayuda

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

use $match para encontrar solo un libro para la misma consulta

 const mongoose = require('mongoose'); const ObjectId = mongoose.Types.ObjectId(); router.get("/:bookId", async (req, res) => { try { let book= await Book.aggregate([ { $match: { _id : ObjectId("book _id") } }, { $lookup: { from: "authors", localField: "authorID", foreignField: "_id", as: "author", }, }, ]); book= book.findById({ _id: req.params.bookId}); res.status(200).json(book); } catch (err) { res.status(404).json({ success: false, msg: "Book is not found" }); } });
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!