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
相关产品推荐
相关产品推荐

