You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS中Post不是构造函数及表单提交验证错误求助

Fixing Your Form Submission Response Issues

Let's break down and resolve both of the problems you're facing with your form submission flow:

1. Fixing TypeError: Post is not a Constructor

The root cause here is how you're importing the Post model. In your Post.js, you're exporting the Mongoose model directly:

module.exports = mongoose.model('Post', PostSchema);

But in Controller.js, you're trying to access a Post property from the imported module, which doesn't exist.

Update your Controller.js import line to:

const Post = require('../models/postModel'); // No .Post needed

2. Fixing ValidationError & Unresponsive Page

This issue has a few interconnected causes—let's address each one:

a. Ensure Form Data is Parsed

Express doesn't automatically parse form-encoded data by default. If you haven't already, add this middleware to your main Express app file (e.g., app.js):

// Parse URL-encoded bodies (form data)
app.use(express.urlencoded({ extended: true }));

Without this, req.body will be empty, which triggers the validation error because all required fields are missing.

b. Correct Flash Message Usage

You're calling flash() directly, but flash messages are attached to the req object via express-session. Replace your flash call with:

req.flash('success-message', 'Yay its fine');

c. Handle Promise Rejections

Your newPost.save() only has a .then() block, but no .catch() to handle validation errors or database issues. This is why your page hangs—when the promise rejects, there's no code to send a response back to the client.

Update your submitPosts function to include error handling:

submitPosts: (req, res) => {
  const newPost = new Post({
    surname: req.body.surname,
    name: req.body.name,
    biography: req.body.biography,
    profilpicture: req.body.profilpicture
  });

  newPost.save()
    .then(post => {
      console.log(post);
      req.flash('success-message', 'Yay its fine');
      res.redirect('/admin');
    })
    .catch(err => {
      // Catch validation errors and flash them
      req.flash('error-message', err.message);
      // Redirect back to the form page so the user can fix issues
      res.redirect('/your-form-page-url'); // Replace with your actual form route
    });
}

d. Double-Check Form Field Names

Even though you mentioned setting the name attributes, double-verify that each input's name exactly matches the fields in your schema (surname, name, biography, profilpicture). A typo here would also cause empty values and validation errors.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:37:47