Mongoose添加User原型方法报Cannot set property 'create' of undefined错如何解决
问题原因与修复方案
核心错误:使用箭头函数定义构造函数
你定义User时使用了箭头函数,这是导致create方法未定义的根本原因:
- 箭头函数没有自身的
prototype原型对象,你执行User.prototype.create = function(){}的操作本质是给不存在的对象赋值,自然无法调用到create方法 - 箭头函数没有独立的
this绑定,也无法通过new关键字作为构造函数实例化,就算解决了原型问题也无法正常使用
其他存在的问题
mongoose.model调用时不需要加new,该方法本身就会返回模型构造函数,多余的new属于无效语法create方法里的await使用错误:new Doc()只是在内存中创建文档实例,是同步操作,真正的异步数据库写入操作是doc.save(),你当前的写法不会将数据写入数据库,也无法捕获写入时的报错
修正后的完整代码
const mongoose = require("mongoose") const userSchema = new mongoose.Schema({ username: { type: String, required: [true, "Field cannot be left blank"], unique: [true, "That username is already taken"], minlength: [3, "Username must be at least 3 characters"], maxlength: [15, "Username cannot exceed 15 characters"], }, }) // 去掉多余的new const Doc = mongoose.model("user", userSchema) // 改为普通构造函数 function User(username) { this.username = username } User.prototype.create = function () { return new Promise(async (resolve, reject) => { try { let doc = new Doc({ username: this.username, }) // 新增save调用,await等待数据库写入完成 await doc.save() resolve(doc) } catch (err) { reject(err) } }) } module.exports = User
调用示例
调用时需通过new关键字实例化User后再调用create方法,示例:
const User = require('./user.js') const testUser = new User('test123') testUser.create().then(res => console.log(res)).catch(err => console.log(err))
内容的提问来源于stack exchange,提问作者Justin Christopher Domingo
相关产品推荐
相关产品推荐

