Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda