mongoose.model()返回undefined,调用findOne时报TypeError错误
问题解决
核心错误
你遇到的 TypeError: Cannot read properties of undefined (reading 'findOne'),根源是Schema文件里的模型创建语法错误:mongoose.model[name, banSchema] 是错误写法,mongoose.model 是方法,不是对象,不能用方括号索引调用,这导致无法正确创建/获取模型,最终导出的是 undefined,调用它的 findOne 自然报错。
修正代码
把模型创建的语法从方括号改为方法调用即可,完整修正后的代码如下:
const mongoose = require('mongoose') const Schema = mongoose.Schema const banSchema = new Schema({ userId: { type: Number, required: true }, reason: { type: String, required: true }, period: { type: String, required: false, default: 'permanent' } }) const name = 'Ban' // 修正方法调用语法 console.log(typeof(mongoose.models[name] || mongoose.model(name, banSchema))) // 现在会输出 'function' // module.exports = mongoose.models[name] || mongoose.model(name, banSchema)
验证说明
修正后,mongoose.model(name, banSchema) 会正确编译Schema并创建名为 Ban 的模型,后续导出的模型对象可以正常调用 findOne 等方法。
内容的提问来源于stack exchange,提问作者KhanPython
相关产品推荐
相关产品推荐

