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

176
Views
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 answers
Answer question

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 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!