Как исправить - TypeError: не удается прочитать комментарии свойства null - PullRequest
0 голосов
/ 02 августа 2020

Создание веб-приложения для блога, и я хотел бы дать возможность комментировать сообщения пользователей. Пытался исследовать и погуглить проблемы, но, похоже, я не могу их решить. Пытался исправить это часами, но я не мог найти решения. Может ли кто-нибудь помочь мне с этой проблемой?

app. js

//Requiring our dependencies
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 4000;

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

//Setting the view engine to ejs
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: false }));

//Connect to mongo
mongoose.connect(dbURI,{ useNewUrlParser: true, useUnifiedTopology: true })
  .then((result) => app.listen(PORT, console.log(`Server started on port ${PORT}. Woo! DB Connected as well.`)))
  .catch((err) => {console.log('Error')})


app.get('/', (req,res) =>{
  Post.find().sort({createdAt: -1})
    .then((result) => {
      res.render('index', {title:'fe', post: result})
    })
    .catch((err) => {
      console.log(err)
    })
});

app.get('/post', (req,res) => {
  res.render('post')
})


app.post('/', (req,res) =>{
  const post = new Post(req.body);
  console.log(post)
  post.save()
    .then((result) => {
      res.redirect('/');
    })
    .catch((err) => {
      console.log(err)
    })
})

app.get('/post/:id', (req,res) => {
  const id = req.params.id;
  Post.findById(id)
    .then(result => {
      res.render('postDetails', {post: result, title: 'Blog Details'})
    })
    .catch(err => {
      console.log(err)
    });
})

// //Create comment
// // CREATE Comment
app.post("/post/:id", function(req, res) {
  // INSTANTIATE INSTANCE OF MODEL
  const comment = new Comment(req.body);
  // console.log(comment)

  Post.findById(req.params.postId)
    .then((post) => {
      post.comments.unshift(comment);
      post.save();
      res.redirect('/')
    })
    .catch(err => {
      console.log(err)
    })
});

Post. js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const PostSchema = new Schema({
       title:{
              type: String, 
              required: true
       },
       summary:{
              type: String, 
              required: true
       },
       comments:[
              {
              type: mongoose.Schema.Types.ObjectId,
              ref: 'Comment'
              }
       ]
}, {timestamps: true});

module.exports = mongoose.model('Post', PostSchema)

Комментарий. js

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

const CommentSchema = new Schema({
  content: {
    type: String, 
    required: 'Content is required'
  },
  post: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Post',
    required: 'Post is required'
  },
});

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

1 Ответ

0 голосов
/ 02 августа 2020

Быстрое исправление: если это происходит на post.comments.unshift (комментарий)

Затем поместите блок кода ente внутри условия if

If (post) {... Ваш код block}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...