【问题标题】:The comment array in the Post does not show the comment id even though the Post and the Comment is linked即使帖子和评论链接,帖子中的评论数组也不显示评论ID
【发布时间】:2022-01-10 10:37:41
【问题描述】:

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)=>{
    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

但是,评论 ID 并未按预期添加到帖子中。 Robo 3T 在 Post 中显示 cmets 的空数组。

/* 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
}

请有人帮我找出为什么评论 ID 没有添加到帖子的 cmets 数组中。

【问题讨论】:

  • commentSchema 似乎只有一个字段 - comment - mongoose 无法知道哪些 cmets 与哪些帖子相关。您可能需要在评论中添加 postId 字段,并在其中发布评论所在的帖子 ID。
  • @Tetarchus 感谢您的评论,但似乎这不是问题的根源。

标签: node.js mongoose post comments


【解决方案1】:

路由器管理错误。它应该是..

router.post('/comments/:id', auth, async(req, res)=>{
    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

这可能不是最好的方法,但至少它有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 2019-08-24
    • 2018-03-20
    • 2023-04-10
    • 1970-01-01
    • 2021-11-02
    • 2015-05-24
    相关资源
    最近更新 更多