【问题标题】:Equivalent of mongoose schema.pre in prisma等价于 prisma 中的 mongoose schema.pre
【发布时间】: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 的项目中解决此类常见问题?

谢谢

【问题讨论】:

标签: node.js mongodb mongoose prisma


【解决方案1】:

离这个问题差不多一年了,但为了那些看起来相同的人:我认为可以使用 Prisma 的自定义模型复制 mongoose 模式方法。您可以在模型中声明方法。还没用过所以无法确认。这是docs

对于没有耐心的人,这里是文档示例:

import { PrismaClient } from '@prisma/client'

type Signup = {
  email: string
  firstName: string
  lastName: string
}

class Users {
  constructor(private readonly prisma: PrismaClient['user']) {}

  // Signup a new user
  async signup(data: Signup): Promise<User> {
    // do some custom validation...
    return this.prisma.create({ data })
  }
}

async function main() {
  const prisma = new PrismaClient()
  const users = new Users(prisma.user)
  const user = await users.signup({
    email: 'alice@prisma.io',
    firstName: 'Alice',
    lastName: 'Prisma',
  })
}

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2011-04-25
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多