【发布时间】: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