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

106
Visualizações
Node JS mongoose create a blog post commenting system

I am trying to build a simple blog with a commenting system with mongoose and express. There is no issse of creating and posting blogs here and each post can be displayed correctly. However, there are some issues associated with comments and each blog. The relationship between comments and blog post was established by applying mongoose.Schema.Types.ObjectId in the post Schema and the comments has been created to store array of comments ids. I think the schema structures are correct and there might be some problems in my code for routing and please help, thanks.

    // Post Schema
    const mongoose = require('mongoose');

    const postSchema = new mongoose.Schema({
      title: {
       type: String,
       trim: true,
       required: true
     },
       text: {
       type: String,
       trim: true,
       required: true
     },
      date: {
       type: Date,
       default: Date.now
     },
      comments: [{
       type: mongoose.Schema.Types.ObjectId,
       ref: 'Comment'
      }]
    })

    postSchema.virtual('url').get(function(){
      return '/post/' + this._id
     })

    module.exports = mongoose.model('Post', postSchema); 


     // Comment Schema 
     
     const mongoose = require('mongoose');

     const commentSchema = new mongoose.Schema({
        text: {
         type: String,
         trim: true,
         required: true
        },
        date: {
         type: Date,
         default: Date.now
         }
        })

      module.exports = mongoose.model('Comment', commentSchema); 

      // Router 

       const express = require('express');
       const Post = require('../models/post');
       const Comment = require('../models/comment');

       const router = new express.Router();


       // Get comments
       router.get('/post/:id/comment', (req, res) => {
           res.render('post-comment', {title: 'Post a comment'})
       })


       // Create and Post comments, this is where I think I made mistakes

       router.post('/post/:id/comment', async (req, res) => {
           const comment = new Comment({text: req.body.text});
           const post = await Post.findById(req.params.id);
           const savedPost = post.comments.push(comment);

           savedPost.save(function(err, results){
              if(err) {console.log(err)}
              res.render('post_details', {title: 'Post details', comments: 
               results.comments})
            } )
          })


        //  Get each post details. 
        // Trying to display comments, but it is all empty and I realized 
        // the comments array is empty, I can see the comments create in 
        // mongodb database why is that?????

       router.get('/post/:id', (req, res) => {
         Post.findById(req.params.id)
             .populate('comments')
             .exec(function(err, results) {
           if(err) {console.log(err)}
             res.render('post_details', {title: 'Post details', post: 
          results, comments: results.comments})
           })
         })

       router.get('/new', (req, res) => {
         res.render('create-post', {title: 'Create a post'})
        })

       router.post('/new', (req, res) => {
         const post = new Post({
          title: req.body.title,
          text: req.body.text
          });
          post.save(function(err) {
           if(err) {console.log(err)}
             res.redirect('/')
          })
         })

       router.get('/', (req, res) => {
          Post.find()
             .exec(function(err, results) {
              if(err) {console.log(err)}

              res.render('posts', {title: 'All Posts', posts: results})
           })
       });

      module.exports = router;
      
over 4 years ago · Santiago Trujillo
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