Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
How to query based on related element's field value?

In my database, every article has its own 6-digit identifying number (in addition to id). Every comment belongs to one of the articles. My question is, how to query comments knowing only the article number, but not the article's id?

controllers/fetch-comments.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');
  }
}

models/article.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);

models/comment.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);

Please do not suggest doing 2 queries intead of one, I already know how to do that.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can use the aggregation framework and use a $match and $lookup operator to get the comment of a particular article number. Following would be the code for the same:

db.Article.aggregate( [


{ $match : { number : article_number} },

{
     $lookup:
   {
     from: "Comment",
     localField: "_id",
     foreignField: "article",
     as: "article_comments"
   }


 }
] )

This will return an array of the matching comments.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda