Node.js+Mongoose用户模型报错:Invalid schema configuration求助
问题排查与修复
错误原因
你遇到的TypeError: Invalid schema configuration错误,根源在于**resetPasswordLink字段的Schema定义不符合Mongoose规则**:
- 当前写法将
resetPasswordLink定义为包含data和default的对象,但data字段未按Mongoose要求显式声明type属性; - 同时
default: ''是给整个resetPasswordLink字段设置默认值,但你实际期望的是给data子字段设默认,类型不匹配导致配置失效。
修复方案
根据业务需求,有两种修改方式:
方案1:resetPasswordLink直接存储字符串(推荐)
如果resetPasswordLink仅用于存储重置链接字符串,直接调整字段定义:
resetPasswordLink: { type: String, default: '', },
方案2:保持嵌套对象结构
如果确实需要用嵌套对象存储,需为data子字段显式声明type:
resetPasswordLink: { data: { type: String, default: '' } },
修改后的完整用户模型示例(方案1)
const mongoose = require('mongoose'); const crypto = require('crypto'); //user schema const userSchema = new mongoose.Schema( { name: { type: String, trim: true, required: true, max: 32, }, email: { type: String, trim: true, required: true, unique: true, lowercase: true, }, hashed_password: { type: String, required: true, }, salt: String, role: { type: String, default: 'subscriber', }, resetPasswordLink: { type: String, default: '', }, }, { timestamps: true } ); //virtual userSchema .virtual('password') .set(function (password) { // create a temporarily variable called _password this._password = password; // generate salt this.salt = this.makeSalt(); // encryptPassword this.hashed_password = this.encryptPassword(password); }) .get(function () { return this._password; }); //methods userSchema.methods = { authenticate: function (plainText) { return this.encryptPassword(plainText) === this.hashed_password; }, encryptPassword: function (password) { if (!password) return ''; try { return crypto .createHmac('sha1', this.salt) .update(password) .digest('hex'); } catch (err) { return ''; } }, makeSalt: function () { return Math.round(new Date().valueOf() * Math.random()) + ''; }, }; module.exports = mongoose.model('User', userSchema);
内容的提问来源于stack exchange,提问作者anikjoyy
相关产品推荐
相关产品推荐

