首页 > 解决方案 > 如何使用 denodb 执行“where”查询?

问题描述

我正在尝试注册用户,但出现错误:

[uncaught application error]: TypeError - Cannot read properties of undefined (reading 'where')

这是代码:

  async register(context: any) {
    const body = JSON.parse(await context.request.body().value);
    const existing = await Users.where("email", body.email).get();

    if (existing.length) {
      context.response.status = 400;
      return (context.response.body = { message: "User already exists" }); 
    }   

    const hashedPassword = await Users.hashPassword(body.password);
    const user = await Users.create({
      email: body.email,
      hashedPassword,
    }); 

    context.response.body = { message: "User created" };
  }

这是我的模型:

// import { Model, DataTypes } from "https://deno.land/x/denodb/mod.ts";
import { DataTypes, Model } from "https://deno.land/x/denodb/mod.ts";
import * as bcrypt from "https://deno.land/x/bcrypt/mod.ts";
import {
  create,
  getNumericDate,
  verify,
} from "https://deno.land/x/djwt/mod.ts";
import { JwtConfig } from "../middleware/jwt.ts";
import { db } from "../db.ts";

class Users extends Model {
  static table = "users";
  static timestamps = true;

  static fields = {
    id: {
      primaryKey: true,
      type: DataTypes.STRING,
    },
    email: {
      type: DataTypes.STRING,
      unique: true,
    },
    hashedPassword: {
      type: DataTypes.STRING,
    },
  };

  static defaults = {
    id: crypto.randomUUID(),
  };

  // ...
  static async hashPassword(password: string) {
    const salt = await bcrypt.genSalt(8);
    return bcrypt.hash(password, salt);
  }

  static generateJwt(id: string) {
    // Create the payload with the expiration date (token have an expiry date) and the id of current user (you can add that you want)
    const payload = {
      id,
      iat: getNumericDate(new Date()),
    };
    // return the generated token
    return create({ alg: "HS512", typ: "JWT" }, payload, JwtConfig.secretKey);
  }
}

//db.link([Users]);
//await db.sync();

export default Users;


标签: denodenodb

解决方案


不得不取消注释:

db.link([Users]);


推荐阅读