本文介绍了我想用mikro-orm插入,但它找不到我的表:C(TableNotFoundException)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以

控制台:

yarn dev
yarn run v1.22.10
$ nodemon dist/index.js
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json  
[nodemon] starting `node dist/index.js`     
[discovery] ORM entity discovery started, using ReflectMetadataProvider
[discovery] - processing entity Post
[discovery] - entity discovery finished, found 1 entities, took 21 ms
[info] MikroORM successfully connected to database postgres on postgresql://postgres:*****@127.0.0.1:5432
[query] begin
[query] insert into "post" ("created_at", "title", "updated_at") values ('2021-04-05T21:04:23.126Z', 'my first post', '2021-04-05T21:04:23.126Z') returning "_id" [took 12 ms]
[query] rollback
TableNotFoundException: insert into "post" ("created_at", "title", "updated_at") values ('2021-04-05T21:04:23.126Z', 'my first post', '2021-04-05T21:04:23.126Z') returning "_id" - relation "post" does not exist
    at PostgreSqlExceptionConverter.convertException (P:.Projekteklireddit-server
[email protected]:36:24)
    at PostgreSqlDriver.convertException (P:.Projekteklireddit-server
[email protected]:194:54)
    at P:.Projekteklireddit-server
[email protected]:198:24
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async PostgreSqlDriver.nativeInsert (P:.Projekteklireddit-server
[email protected]:150:21)
    at async ChangeSetPersister.persistNewEntity (P:.Projekteklireddit-server
[email protected]:55:21)
    at async ChangeSetPersister.executeInserts (P:.Projekteklireddit-server
[email protected]:24:13)
    at async UnitOfWork.commitCreateChangeSets (P:.Projekteklireddit-server
[email protected]:496:9)
    at async UnitOfWork.persistToDatabase (P:.Projekteklireddit-server
[email protected]:458:13)
    at async PostgreSqlConnection.transactional (P:.Projekteklireddit-server
[email protected]:53:25)
    at async UnitOfWork.commit (P:.Projekteklireddit-server
[email protected]:183:17)
    at async SqlEntityManager.flush (P:.Projekteklireddit-server
[email protected]:486:9)
    at async SqlEntityManager.persistAndFlush (P:.Projekteklireddit-server
[email protected]:438:9)

previous error: insert into "post" ("created_at", "title", "updated_at") values ('2021-04-05T21:04:23.126Z', 'my 
first post', '2021-04-05T21:04:23.126Z') returning "_id" - relation "post" does not exist
    at Parser.parseErrorMessage (P:.Projekteklireddit-server
ode_modulespg-protocoldistparser.js:278:15)   
    at Parser.handlePacket (P:.Projekteklireddit-server
ode_modulespg-protocoldistparser.js:126:29)        
    at Parser.parse (P:.Projekteklireddit-server
ode_modulespg-protocoldistparser.js:39:38)
    at Socket.<anonymous> (P:.Projekteklireddit-server
ode_modulespg-protocoldistindex.js:10:42)
    at Socket.emit (events.js:315:20)
    at Socket.EventEmitter.emit (domain.js:467:12)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9)
    at Socket.Readable.push (internal/streams/readable.js:223:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:188:23) {
  length: 166,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '13',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'd:\pginstaller_13.auto\postgres.windows-x64\src\backend\parser\parse_relation.c',
  line: '1376',
  routine: 'parserOpenTable'
}

Index.ts:

import { MikroORM } from "@mikro-orm/core";
import { __prod__ } from "./constants";
import { Post } from "./entities/Post";
import mikroConfig from "./mikro-orm.config";

const main = async () => {
  const orm = await MikroORM.init(mikroConfig);
  await orm.getMigrator().up;
  const post = orm.em.create(Post, { title: "my first post" });
  await orm.em.persistAndFlush(post);
};

main().catch((err) => {
  console.error(err);
});

Post.ts:

import { Entity, PrimaryKey, Property } from "@mikro-orm/core";

@Entity()
export class Post {
  @PrimaryKey()
  _id!: number;

  @Property({ type: "date" })
  createdAt = new Date();

  @Property({ type: "date", onUpdate: () => new Date() })
  updatedAt = new Date();

  @Property({ type: "text" })
  title!: string;
}

mikro-orm.config.ts:

import { __prod__ } from "./constants";
import { Post } from "./entities/Post";
import { MikroORM } from "@mikro-orm/core";
import path from "path";

export default {
  migrations: {
    path: path.join(__dirname, "./migrations"),
    pattern: /^[w-]+d+.[tj]s$/,
  },
  entities: [Post],
  dbName: "postgres",
  debug: !__prod__,
  type: "postgresql",
  password: "hellothere",
} as Parameters<typeof MikroORM.init>[0];

和我使用npx mikro-orm创建的迁移:创建:

import { Migration } from '@mikro-orm/migrations';

export class Migration20210405205411 extends Migration {

  async up(): Promise<void> {
    this.addSql('create table "post" ("_id" serial primary key, "created_at" timestamptz(0) not null, "updated_at" timestamptz(0) not null, "title" text not null);');
  }

}

之后我把它编译成js btw,但我猜问题可能出在我的代码或idk的某个地方,请帮助我,我可以给你更多的信息请帮助,我已经试着修复这个错误5个小时了:/

推荐答案

我也遇到过同样的问题。我是这样做的:

  1. 我删除了migrations文件夹和dist文件夹
  2. 我运行了npx mikro-orm migration:create --initial

之后,我重新启动了yarn watchyarn dev,它对我起作用。

请注意--initial标志。我建议您检查official documentation。迁移表用于跟踪已执行的迁移。仅运行npx mikro-orm migration:create时,将不会创建表,因此MikroORM无法检查Post实体的迁移是否已执行(包括在数据库上创建相应的表)。

Ben在他的教程中没有使用--initial标志,他可能已经在教程之前运行了它。

这篇关于我想用mikro-orm插入,但它找不到我的表:C(TableNotFoundException)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 09:32