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

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

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