请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

TypeORM v0.3.12 按照文档里写的,报错 No metadata for "Auth" was found.

import {
	Column, ManyToOne, JoinColumn,
	Entity, PrimaryGeneratedColumn
} from "typeorm";
import { User } from "./user";

@Entity({ name: "auths" })
export class Auth {
    @PrimaryGeneratedColumn() readonly id!: number;
    @Column() user_id!: string;
    @Column() type!: string;
    @Column() identifier!: string;
    @Column() credential!: string;
    @ManyToOne(() => User, { cascade: true })
    @JoinColumn({ name: "user_id" }) user!: User;
}
import "reflect-metadata";
import { DataSource } from "typeorm";
import { ConnectionOpts } from "@/scripts/config";
import { User } from "./entity/user";
import { Auth } from "./entity/auth";

const entities = [User, Auth];
const options = { ...ConnectionOpts, entities };
const AppDataSource = new DataSource(options);
export default AppDataSource;
import AppDataSource from "@/database";
import { User } from "@/database/entity/user";
import { Auth } from "@/database/entity/auth";
import { tSession } from "@/scripts/types";

async function login(req: NextApiRequest, res: NextApiResponse) {
    const { type, mobile, verify } = req.body;
    const userRepository = AppDataSource.getRepository(User);
    const authRepository = AppDataSource.getRepository(Auth);
    const session: tSession = req.session;
    
    if (session.verifyCode === verify) {
        const condition = { type, identifier: mobile };
        // 运行到这个查找语句,就报错:No metadata for "Auth" was found.
        const authRes = await authRepository.findOneBy(condition);
    }
}

查了下资料,说是通常因为实体没有正确的定义、导入或注册引起的。
但是我看了好几遍,没看出什么问题来。不知道怎么办,求老师指导。

正在回答 回答被采纳积分+3

2回答

Tomas 2023-03-31 12:54:10

[Auth, User]

0 回复 有任何疑惑可以回复我~
Tomas 2023-03-31 12:53:34

Auth 表里面有用 user 信息,你在 entity 注册那里调整一下它俩的顺序试试呢

0 回复 有任何疑惑可以回复我~
  • 提问者 VyingGao #1
    刚刚试了下,不行的。之前出问题的时候,换成在用户表里查找 const userRes = await userRepository.findOneBy(condition); 就会报错 No metadata for "User" was found.
    回复 有任何疑惑可以回复我~ 2023-03-31 13:28:39
  • 提问者 VyingGao #2
    刚刚又去看了下文档,发现那些数据库操作,要放在它的函数里执行才可以。
    AppDataSource.initialize().then(async () => {
        const condition = { type, identifier: mobile };
        const authRes = await authRepository.findOneBy(condition);
    }).catch(error => console.log(error));
    文档里的示例都比较简单,不知道是不是每次做数据库操作都要套一下
    回复 有任何疑惑可以回复我~ 2023-03-31 17:41:13
  • Tomas #3
    嗯嗯 最近工作太忙了,抽时间我也看下哈
    回复 有任何疑惑可以回复我~ 2023-04-03 17:52:06
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信