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

使用Express+Postman向MongoDB插入数据报'title'未定义错误如何解决?

错误根因

TypeError: Cannot read property 'title' of undefined报错的核心原因是Express未配置JSON请求体解析中间件,导致接收Postman请求时req.body为未定义状态,和Schema类型、Postman配置无直接关联。

修复步骤

  1. 修正app.js的中间件顺序与配置
    Express 4.16及以上版本内置了请求体解析能力,无需单独安装body-parser,在挂载路由前添加解析中间件,同时调整中间件执行顺序,确保自定义中间件调用next()传递请求:
const express = require('express');
const app = express();
const Mongoose = require('mongoose');
require('dotenv/config')
const postsRoute = require('./routes/posts');

// 新增:请求体解析中间件,必须放在路由挂载之前
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 调整:自定义中间件放在路由之前,且添加next()避免请求卡死
app.use('/posts', (req, res, next) => {
    console.log('This is a middleware.')
    next();
})
// 路由挂载放在所有中间件之后
app.use('/posts', postsRoute)

app.get('/', (req, res) => {
    res.send('We are at home')
})

//Connect to DB
Mongoose.connect(process.env.DB_CONNECTION)
.then(() => {
    console.log('connected to DB')
})
.catch(err => {
    console.log(err);
});


app.listen(3000);
  1. 修正Mongoose Schema字段类型
    普通文本字段无需设置为JSON类型,改为String即可匹配常规请求参数:
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    }
});

module.exports = mongoose.model('Posts', PostSchema);
  1. 确认Postman请求格式
    发送POST请求时,Body选项卡选择raw,格式下拉选JSON,请求体符合JSON格式即可。

修改完成后重启服务,即可正常插入数据。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:57:02