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