【发布时间】:2022-04-16 09:54:31
【问题描述】:
我基本上定义了这个模型,就像另一个不会出错的模型;所以我很困惑为什么它不起作用......
这是Minimal, Reproducible Example
不工作:
import mongoose from 'mongoose';
const TokenSchema = new mongoose.Schema({
_userId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
token: { type: String, required: true },
createdAt: { type: Date, required: true, default: Date.now, expires: 43200 }
});
export default mongoose.models.Token || mongoose.model('Token', TokenSchema);
工作:
import mongoose from 'mongoose';
import emailValidator from 'email-validator'
import bcrypt from 'bcrypt'
import crypto from 'crypto'
const SALT_ROUNDS = 12;
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
trim: true,
lowercase: true,
index: { unique: true },
validate: {
validator: emailValidator.validate,
message: props => `${props.value} is not a valid email address!`
}
},
password: {
type: String,
required: true,
trim: true,
index: { unique: true },
minlength: 7,
maxlength: 11
},
roles: [{ type: 'String' }],
isVerified: { type: Boolean, default: false },
passwordResetToken: String,
resetPasswordExpires: Date
},
{
timestamps: true
}
);
UserSchema.pre('save', async function preSave(next) {
const user = this;
if (!user.isModified('password')) return next();
try {
const hash = await bcrypt.hash(user.password, SALT_ROUNDS);
user.password = hash;
return next();
} catch (err) {
return next(err);
}
});
UserSchema.methods.generatePasswordReset = function () {
this.resetPasswordToken = crypto
.randomBytes(20)
.toString('hex');
this.resetPasswordExpires = Date.now() + 3600000; // expires in an hour
};
UserSchema.methods.comparePassword = async function comparePassword(candidate) {
return bcrypt.compare(candidate, this.password);
};
export default mongoose.models.User || mongoose.model('User', UserSchema)
我还在 Next.js 示例存储库中关注此 example。
请帮忙! :)
【问题讨论】:
-
你解决了这个问题吗?我遇到了同一个...
-
@andrewnosov 嘿,我做到了——查看我的仓库,here 如果该语法不适合您,请告诉我。它也可能是一个版本的东西。 !干杯!
-
谢谢!我通过将直接使用的函数代码移动到请求文件来解决我的问题。不知道这是如何工作的,但问题消失了。
标签: javascript mongodb mongoose next.js mongoose-schema