【发布时间】:2021-06-03 02:36:30
【问题描述】:
我最近将我的副项目从 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,
required: true,
lowercase: true,
unique: true,
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 的项目中解决此类常见问题?
谢谢
【问题讨论】:
-
在Prisma middleware 上查看此部分,这应该适合您的用例。
标签: node.js mongodb mongoose prisma