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

175
Views
¿Cómo consultar en función del valor del campo del elemento relacionado?

En mi base de datos, cada artículo tiene su propio número de identificación de 6 dígitos (además de la identificación). Cada comentario pertenece a uno de los artículos. Mi pregunta es, ¿cómo consultar comentarios sabiendo solo el número de artículo, pero no la identificación del artículo?

controladores/buscar-comentarios.js:

 const Article = require('../models/article') const User = require('../models/user'); const Comment = require('../models/comment'); module.exports = async function (req, res) { try { let { article_number, articleId } = req.body let filter; console.log(article_number) /* Here is my failed attempt: */ if (article_number) filter = { 'article.number': article_number }; if (articleId) filter = { 'article': articleId }; let projection = null let options = null let comments = await Comment.find(filter, projection, options).populate('author', 'username fullname').lean() return res.status(200).send(comments) } catch (error) { console.log("error on getting comments: " + error.message); return res.status(500).send('Server side error'); } }

modelos/artículo.js:

 const mongoose = require('mongoose'); const Schema = mongoose.Schema; const articleSchema = new Schema({ author: { type: Schema.Types.ObjectId, ref: 'User', required: true }, title: { type: String, required: true }, content: { type: String, required: true }, coverPhotoUrl: { type: String, required: false }, number: { type: Number, required: true }, // number is public id for address bar createdAt: { type: Date, required: true }, category: { type: String, required: false }, fake: { type: Boolean, required: false }, }); module.exports = mongoose.model('Article', articleSchema);

modelos/comentario.js:

 const mongoose = require('mongoose'); const Schema = mongoose.Schema; const commentSchema = new Schema({ author: { type: Schema.Types.ObjectId, ref: 'User', required: true }, content: { type: String, required: true }, createdAt: { type: Date, required: true }, article: { type: Schema.Types.ObjectId, ref: 'Article', required: true } }); module.exports = mongoose.model('Comment', commentSchema);

No sugiera hacer 2 consultas en lugar de una, ya sé cómo hacerlo.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Puede usar el marco de agregación y usar un operador $match y $lookup para obtener el comentario de un número de artículo en particular. El siguiente sería el código para el mismo:

 db.Article.aggregate( [ { $match : { number : article_number} }, { $lookup: { from: "Comment", localField: "_id", foreignField: "article", as: "article_comments" } } ] )

Esto devolverá una matriz de los comentarios coincidentes.

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!