Массив комментариев в сообщении не показывает идентификатор комментария, даже если сообщение и комментарий связаны

#node.js #mongoose #post #comments

#node.js #мангуст #Публикация #Комментарии

Вопрос:

Модель Post.js является

 const mongoose = require('mongoose')  const postSchema = new mongoose.Schema({  title: {  type: String,  required: true,  trim: true  },  content: {  type: String,  required: true,  },  postedBy: {  type: mongoose.Schema.Types.ObjectId,  required: true,  ref: 'User'  },  comments: [{  type: mongoose.Schema.Types.ObjectId,  ref: 'Comment'  }] })  const Post = mongoose.model('Post', postSchema)  module.exports = Post  

Модель Comment.js является

 const mongoose = require('mongoose')  const commentSchema = new mongoose.Schema({  comment: String })   const Comment = mongoose.model('Comment', commentSchema)  module.exports = Comment  

Маршрутизатором добавления комментария является:

 const express = require('express') const Comment = require('../models/comment') const auth = require('../middleware/auth') const router = new express.Router()  router.post('/comments/:id', auth, async(req, res)=gt;{  const comment = new Comment(req.body)  try {  await comment.save()  res.status(201).send(comment)  } catch (e){  res.status(400).send(e)  } })  module.exports = router  

Комментарий отправляется почтальоном, как показано ниже.

 {{url}}/comments/61ab30166760b4f9fc40060f  

Идентификатор комментария, однако, не добавляется в сообщение, как ожидалось. Робот 3T показывает пустой массив комментариев в сообщении.

 /* 1 */ {  "_id" : ObjectId("61ab30096760b4f9fc40060a"),  "title" : "jstesting the blog the 1st time",  "content" : "jstesting how the node and mongoose are interacting the 1st time",  "postedBy" : ObjectId("61ab2fd06760b4f9fc4005f7"),  "comments" : [],  "__v" : 0 }  /* 2 */ {  "_id" : ObjectId("61ab30166760b4f9fc40060f"),  "title" : "jstesting the blog the 2nd time",  "content" : "jstesting how the node and mongoose are interacting the 2nd time",  "postedBy" : ObjectId("61ab2fd06760b4f9fc4005f7"),  "comments" : [],  "__v" : 0 }  

Кто — нибудь, пожалуйста, помогите мне найти, почему идентификатор комментария не добавляется в массив комментариев поста.

Комментарии:

1. commentSchema похоже, у него есть только одно поле comment mongoose нет возможности узнать, какие комментарии относятся к каким публикациям. Вероятно, вам потребуется добавить postId поле в комментарий, в котором вы размещаете идентификатор записи, на которой находится комментарий.

2. @Tetarchus Спасибо за ваш комментарий, но, похоже, это не было источником проблемы.

Ответ №1:

Управление маршрутизатором было неправильным. Это должно быть так ..

 router.post('/comments/:id', auth, async(req, res)=gt;{  const comment = new Comment(req.body)  try {  const post = await Post.findOne({  _id: req.params.id,  })   if(!post){  return res.status(404).send()  }    post.comments.push(comment._id)   await post.save()  await comment.save()   res.status(201).send(comment)  } catch (e){  res.status(400).send(e)  } })  module.exports = router  

Возможно, это не лучший подход, но, по крайней мере, он работает.