You need to enable JavaScript to run this app. Node.js+EJS项目中如何实现表单无刷新提交并存储数据到MongoDB
优惠活动
大模型
产品
解决方案
定价
更多

Node.js+EJS项目中如何实现表单无刷新提交并存储数据到MongoDB

修复步骤

1. 修复路径不匹配问题

你前端AJAX请求的路径是/post/do-comment,但后端定义的接收路由是/do-comment,路径不一致导致请求失败,触发表单默认提交行为,所以页面会自动刷新。

2. 修复MongoDB更新语法错误

你使用$push操作符时没有指定要插入的数组字段名,导致数据无法正常存入Blog文档。需要确认你Blog模型中存储评论的数组字段名(假设字段名为comments,可根据你的实际定义调整)。

3. 增加错误捕获和用户反馈

给后端接口加异常捕获,前端AJAX加错误回调,方便排查问题,同时提交成功后自动追加新评论到页面,无需手动刷新。


修复后代码

Node.js 接口代码

app.post("/do-comment", async (req,res) =>{      
  try {
    const comment = new Comment({
      name: req.body.name,
      comment: req.body.comment
    });
    await comment.save();
    // 此处comments为Blog模型中存储评论的数组字段名,需和你实际定义的字段名一致
    await Blog.findOneAndUpdate({_id: req.body._id}, {$push: {comments: comment}});
    res.json({
      code: 200,
      msg: "评论提交成功",
      data: comment
    });
  } catch (err) {
    console.error('评论保存失败:', err);
    res.status(500).json({
      code: 500,
      msg: "评论保存失败,请重试"
    })
  }
})

前端JS代码

function doComment(form){
  $.ajax({
    // 修正请求路径和后端一致
    url:"/do-comment",
    method:"POST",
    data:{
      name: form.name.value,
      comment: form.comment.value,
      _id: form._id.value
    },
    success: function(response){
      alert(response.msg);
      // 自动追加新评论到评论区
      const newComment = `
        <h1>${response.data.name}</h1>
        <p>${response.data.comment}</p>
      `;
      // 选择评论区容器插入新评论
      document.querySelector('.container-fluid').insertAdjacentHTML('beforeend', newComment);
      // 清空表单
      form.reset();
    },
    error: function(xhr) {
      alert(xhr.responseJSON?.msg || '提交失败,请稍后重试');
    }
  });
  return false;
}

额外注意事项

确认你的Blog模型中已经定义了评论存储的数组字段,示例如下:

// Blog模型定义示例
const mongoose = require('mongoose');
const blogSchema = new mongoose.Schema({
  title: String,
  content: String,
  image: Object,
  // 评论数组字段,字段名要和接口中$push的字段名保持一致
  comments: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment'
  }]
})
const Blog = mongoose.model('Blog', blogSchema);

内容的提问来源于stack exchange,提问作者Tushar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 15:45:03