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

270
Views
Mongoose One-to-Many, cómo obtener el valor de campo de la categoría

Tengo 2 colecciones: Categoría y libro.

Libro:

 const mongoose = require('mongoose'); // eslint-disable-next-line camelcase const mongoose_delete = require('mongoose-delete'); const { Schema } = mongoose; const SchemaTypes = mongoose.Schema.Types; const Book = new Schema({ name: { type: String }, price: { type: Number }, images: { type: Array }, country: { type: String }, author: { type: String }, publicationDate: { type: String }, description: { type: String }, category: { type: SchemaTypes.ObjectId, ref: 'Category' }, date: { type: Date, default: Date.now }, }, { timestamps: true, }); Book.plugin(mongoose_delete); Book.plugin(mongoose_delete, { overrideMethods: 'all', deletedAt: true }); module.exports = mongoose.model('Book', Book);

Categoría:

 const mongoose = require('mongoose'); // eslint-disable-next-line camelcase const mongoose_delete = require('mongoose-delete'); const SchemaTypes = mongoose.Schema.Types; const { Schema } = mongoose; const Category = new Schema({ name: { type: String, required: true }, image: { type: String }, products: [{ type: SchemaTypes.ObjectId, ref: 'Book' }], date: { type: Date, default: Date.now }, }, { timestamps: true, }); Category.plugin(mongoose_delete); Category.plugin(mongoose_delete, { overrideMethods: 'all', deletedAt: true }); module.exports = mongoose.model('Category', Category);

y selecciono todos los libros recibidos de la lista:

 { _id: new ObjectId("623668ac5b1d392b37690cbc"), name: 'The Godfather', price: 110000, country: 'U.S', publicationDate: '1969', category: new ObjectId("6238fdf64f60303756b60b20"), author: 'Mario Puzo', ... : ... }

Y quiero mostrar el nombre de la categoría en la lista de productos, ¿cómo lo hago? **como: {{book.category.name}}

{{libro.categoría.imagen}}

?**

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

prueba $búsqueda (agregación)

 Book.aggregate([{ $lookup: { from: "Category", localField: "category", foreignField: "_id", as: "category" } }]).exec(function(err, students) { });
over 4 years ago · Santiago Trujillo Report

0

Como está usando Mongoose, puede usar el método populate() . Puedes hacerlo así:

 const books = await Books.find().populate('category')
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!