繁体   English   中英

在 mongodb nodejs 中向博客添加评论

[英]add comments to blog in mongodb nodejs

我想创建一个人们可以评论的博客。 我用 ajax 发送数据到 controller 也收到了 controller 端的数据。 但问题是接收到的数据没有插入数据库我认为问题出在 controller 因为我在 controller 中收到了数据,我是 nodejs 的新手,您的帮助将受到高度赞赏!

这是控制台中打印的数据https://prnt.sc/11abe59

<form method="POST" onsubmit="return doComment(this);" class="theme-form-one">
    <input type="hidden" name="_id" value="{{blog._id}}">
        <div class="row">
         <div class="col-md-6 col-12"><input type="text" name="name" placeholder="Name"></div>
         <div class="col-12"><input type="email" name="email"  placeholder="Email"></div>
         <div class="col-12"><textarea name="comment" placeholder="Comments"></textarea></div>
      </div>
    <button class="theme-button-one">POST COMMENT</button>
</form>

这是我的 ajax 文件发送数据到 controller

<script>
    function doComment(form){
    $.ajax({
    url:"/blog/do-comment",
    method:"POST",
    data:{name:form.name.value,email:form.email.value,comment:form.comment.value,
        _id:form._id.value},
    success: function(response){
    alert(response);
        }
    });
    return false;
}
</script>

这是我的 controller

router.post("/do-comment",(req,res) =>{
    console.log(req.body)
       Blog.findOneAndUpdate({_id:req.body._id},{Comment:{name:req.body.name,
        email:req.body.email,
        comment:req.body.comment},
         
           function(error,post){
              res.send("Comment Succssfully")
          }
       })
})

博客架构

var BlogSchema = new mongoose.Schema({
    title:{
        type:String,
        required: "this field is required"
    },
    description:{
        type:String,
        required: "this field is required"
    },
    img:{
        type:String,
        required:"this filed is required"
    },
    comment:[
        {
            type:mongoose.Schema.Types.ObjectId, ref:'Comment'
        }
    ]
},{
    timestamps: true
    
})

评论模式

var commentSchema = new mongoose.Schema({
    name:{
        type:String,
        required: "this field is required"
    },
    email:{
        type:String,
        required: "this field is required"
    },
    comment:{
        type:String,
        required:"this filed is required"
    },
    blog:{
        type:mongoose.Schema.Types.ObjectId,
        ref: 'Blog'
    }

},{
    timestamps: true
    
})

目前,您实际上并没有创建新评论,也没有将新评论推送到comment数组,这就是评论没有保存到数据库的原因。 将其更改为:

router.post("/do-comment", async (req,res) =>{      
    const comment = new Comment({name:req.body.name, email:req.body.email, comment:req.body.comment});
    await comment.save();
    await Blog.findOneAndUpdate({_id:req.body._id}, {$push: {comment});
    res.send("Comment was added successfully");
})  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM