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

Nodejs+Express+Mongoose开发联系表单报.cache is not a function错误如何解决

错误排查与解决方案

根因定位

报错的直接原因是代码拼写错误:Promise 异步操作的错误捕获方法为 .catch(),你在编写时误写为 .cache(),JavaScript 运行时找不到不存在的 cache 方法,因此抛出类型错误。

修复步骤

修改 App.js 中 POST 接口的逻辑代码,找到如下片段:

app.post('/', (req, res) => {
    var myData = new Contact(req.body);
    myData.save().then(()=>{
        res.send("This Data has been saved")
    }).cache(()=>{
        res.status(400).send("Item was not saved into DB")
    })    
})

将其中的 .cache 替换为 .catch 即可,修改后代码如下:

app.post('/', (req, res) => {
    var myData = new Contact(req.body);
    myData.save().then(()=>{
        res.send("This Data has been saved")
    }).catch(()=>{
        res.status(400).send("Item was not saved into DB")
    })    
})

额外优化建议

  • 你定义的 contactSchema 中包含 phone 字段,但前端 Pug 表单中没有对应输入项,存储数据时该字段会为空,可根据需求补全表单字段。
  • 可添加 Mongoose 连接错误监听逻辑,方便排查数据库连接异常:
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => console.log('MongoDB connected successfully'));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 14:06:05