Mongose Works
Published: 2022-03-04 13:22:26

I am trying to build a simple blog with a commenting system with mongoose and express. There is no issue 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;
      


`