@longroadhome

Как решить ошибку Sequelize nodejs: TypeError: Cannot convert undefined or null to object?

Модель данных, в которой происходит ошибка:

import { Column, DataType, Model, Table } from "sequelize-typescript";

@Table({
  tableName: "room",
})
class Room extends Model {
  public static ROOM_TABLE_NAME = "room";
  public static ROOM_ID = "id";
  public static ROOM_NAME = "name";

  @Column({
    type: DataType.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    field: Room.ROOM_ID,
  })
  id!: number;

  @Column({
    type: DataType.STRING(100),
    field: Room.ROOM_NAME,
  })
  name!: string;
}

export default Room;


config для базы

import { Sequelize } from "sequelize-typescript";
import * as dotenv from "dotenv";
import Room from "../models/room";

dotenv.config();

class Database {
  public sequelize: Sequelize | undefined;

  private POSTGRES_DB = process.env.POSTGRES_DB;
  private POSTGRES_HOST = process.env.POSTGRES_HOST;
  private POSTGRES_PORT = process.env.POSTGRES_PORT;
  private POSTGRES_USER = process.env.POSTGRES_USER;
  private POSTGRES_PASSWORD = process.env.POSTGRES_PASSWORD;

  constructor() {
    this.connectToPostgresSql();
  }

  private async connectToPostgresSql() {
    try {
      this.sequelize = new Sequelize({
        database: this.POSTGRES_DB,
        username: this.POSTGRES_USER,
        password: this.POSTGRES_PASSWORD,
        host: this.POSTGRES_HOST,
        port: Number(this.POSTGRES_PORT),
        dialect: "postgres",
        models: [Room],
      });

      await this.sequelize.authenticate();

      console.log("✅ PostgreSQL connection has been established successully");
    } catch (error) {
      console.log("❌ Unable to connect to postgreSQL database", error);
    }
  }
}

export default Database;


index.ts

import express from "express";
import http from "http";
import { Server, Socket } from "socket.io";
import cors from "cors";
import RoomRouter from "./src/router/room-router";
import { userHandlers as registerUserHandlers } from "./src/socket-handlers";
import { cardHandlers as registerCardHandlers } from "./src/socket-handlers";
import Database from "./src/config/database";

const db = new Database();

const app = express();
const httpServer = http.createServer(app);
const io = new Server(httpServer, {
  cors: {},
});

app.use(cors());
app.use("/api/v1/room", RoomRouter);

io.on("connection", (socket) => {
  console.log(`Client connected: ${socket.id}`);

  const { roomId } = socket.handshake.query;

  Object.defineProperty(socket, "roomId", {
    value: roomId,
    writable: true,
    enumerable: true,
    configurable: true,
  });

  if (typeof roomId === "string") {
    socket.join(roomId);
  }

  registerUserHandlers({ io, socket: socket as Socket & { roomId: string } });
  registerCardHandlers({ io, socket: socket as Socket & { roomId: string } });
});

const startServer = async () => {
  await db.sequelize?.sync();
  httpServer.listen(3000, () => {
    console.log("Server started on port 3000");
  });
};

startServer();


Непосредственно ошибка:

primaryKey: true,
                                       ^
TypeError: Cannot convert undefined or null to object
    at Function.getOwnPropertyDescriptor (<anonymous>)
    at /Users/azharchenko/Documents/projects/planning-poker-back/node_modules/sequelize-typescript/dist/model/column/column.js:18:131
    at __esDecorate (/Users/azharchenko/Documents/projects/planning-poker-back/src/models/room.ts:13:40)
    at /Users/azharchenko/Documents/projects/planning-poker-back/src/models/room.ts:17:3
    at /Users/azharchenko/Documents/projects/planning-poker-back/src/models/room.ts:80:7
    at Object.<anonymous> (/Users/azharchenko/Documents/projects/planning-poker-back/src/models/room.ts:88:3)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Object.require.extensions.<computed> [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:1621:12)
  • Вопрос задан
  • 419 просмотров
Решения вопроса 1
@longroadhome Автор вопроса
Проблема решилась тупо очень
Не было tsconfig.json (хз как так)
Если что (на всякий случай) - он вот такой

пофиксил вывалившиеся ошибки в консоли и всё ок стало

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "resolveJsonModule": true,

    /* Language and Environment */
    "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,

    /* Modules */
    "module": "commonjs" /* Specify what module code is generated. */,
    "outDir": "./build" /* Specify an output folder for all emitted files. */,
    "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
    "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,

    /* Type Checking */
    "strict": true /* Enable all strict type-checking options. */,
    "skipLibCheck": true /* Skip type checking all .d.ts files. */
  }
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы