如何解决等效于 Prisma 中的 mongoose schema.pre
我最近将我的副项目从 MongoDB (mongoose) 切换到 PostgreSQL。为了避免编写原始 SQL 查询,我不得不选择一个 ORM。当前选项是 Sequelize、TypeORM 和 Prisma。我倾向于 Prisma 并开始学习一些教程。
我遇到了一个问题,我试过谷歌,但我没能找到答案。
在像这样将数据保存到 mongo 文档之前,您知道通常如何执行某些操作
const userSchema = new mongoose.Schema<IUser>(
{
_id: mongoose.Schema.Types.ObjectId,username: {
type: String,required: true,unique: true,trim: true,index: true,lowercase: true,},email: {
type: String,match: /[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?/,....
);
userSchema.pre("save",async function (next) {
// If the password wasn't modified,no need to regenerate the password with another salt
if (!this.isModified("password")) return next();
const salt = await bcrypt.genSalt();
this.password = await bcrypt.hash(this.password,salt);
this.salt = salt;
});
基本上,我想加密密码而不必在控制器中进行。或者一般来说,像这样对文档执行操作的方法。
userSchema.methods.matchPassword = async function (rawPassword) {
try {
return await bcrypt.compare(rawPassword,this.password);
} catch (err) {
throw new Error(err.message);
}
};
这些可以用 Prisma 实现吗?如果不是,您如何在使用 Prisma 的项目中解决此类常见问题?
谢谢
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。