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

Mongoose模型报错TypeError: User is not a constructor 求解决方案

解决Mongoose中「TypeError: User is not a constructor」错误

问题核心原因

你当前代码的直接错误是在user-controller.js中引入User模型时,仅写了文件路径字符串,没有通过require()方法加载模块,导致User只是一个字符串而非Mongoose模型构造函数。

修正后的代码

user-controller.js

const uuid = require('uuid')
const bcrypt = require('bcrypt')
const saltRounds = 12;

// 修正:添加require()加载模型
const User = require('../models/user')

async function registerUser(req, res, next) {
    const {displayName, password} = req.body;
    const hash = await bcrypt.hash(password, saltRounds)
    const newUser = new User({
        displayName: displayName,
        password: hash,
        uuid: uuid.v4()
    });

    const response = await newUser.save();

    res.json({
        message: "registration success",
        userCreated: newUser
    })
}

额外排查点(若修正后仍有问题)

  • 确认模型文件路径是否正确:如果user-controller.js和models文件夹不在同一层级,需调整路径(比如./models/user或../../models/user)
  • 确认模型导出方式:你的user.js中module.exports = mongoose.model('User', userSchema)是正确的导出方式,无需修改

错误信息回顾

TypeError: User is not a constructor

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:40:31