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

201
Views
Mongoose many to many relation

I am beginner Node.JS and Mongoose programmer. So far I have created a very simple blog with 3 Models - Article, User, Categories and everything is working fine. Now I want to create comments. So I want every user to be able to have manny comments and every articles also to be able to have manny comments. How can I do that and how can I represent logic in the controller to interact with each other:

let articleSchema = mongoose.Schema (
{
    author: {type: ObjectId, ref: 'User'},
    title: {type: String, required: true },
    content: {type: String, required: true },
    category: {type: ObjectId, ref: 'Category', required: true},
    date: {type: Date, default: Date.now() },
}
);

let userSchema = mongoose.Schema(
{
    email: {type: String, required: true, unique: true},
    passwordHash: {type: String, required: true},
    fullName: {type: String, required: true},
    salt: {type: String, required: true},
    articles: [{type: ObjectId, ref: 'Article'}],
    roles: [{type: ObjectId, ref: 'Role'}]
}
);

let categorySchema = mongoose.Schema (
{
    name: {type: String, required:true},
    articles: [{type: ObjectId, ref: 'Article'}]
}
); 
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Create Comment schema which will reference Author and Article:

let commenSchema = mongoose.Schema (
{
    author: {type: ObjectId, ref: 'User', required: true},
    content: {type: String, required: true },
    article: {type: ObjectId, ref: 'Article', required: true},
    date: {type: Date, default: Date.now() },
});
about 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!