PostgreSQL - 带连接表的SequelizeDatabaseError(代码:42P01)

时间:2017-11-15 04:03:51

标签: postgresql sequelize.js

我正在尝试为多对多关系创建连接表。

我收到以下错误:

"name": "SequelizeDatabaseError",
"parent": {
    "name": "error",
    "length": 110,
    "severity": "ERROR",
    "code": "42P01",
    "position": "13",
    "file": "parse_relation.c",
    "line": "1160",
    "routine": "parserOpenTable",
    "sql": "INSERT INTO \"user_routes\" (\"id\",\"userId\",\"routeId\",\"createdAt\",\"updatedAt\") VALUES (DEFAULT,'1','1','2017-11-15 03:57:21.791 +00:00','2017-11-15 03:57:21.791 +00:00') RETURNING *;"
},

关系介于UserRoute之间:

module.exports = (sequelize, DataTypes) => {
  const Route = sequelize.define("Route", {
    open: {
      type: DataTypes.BOOLEAN,
      allowNull: true
    }
  });

  Route.associate = models => {
    Route.belongsToMany(models.User, {
      through: "userRoutes",
      as: "users"
    });
  };
  return Route;
};


module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define("User", {
    email: DataTypes.TEXT,
    password: DataTypes.TEXT
  });

  User.associate = models => {
    User.belongsToMany(models.Route, {
      through: "userRoutes",
      as: "routes"
    });
  };

  return User;
};

用户和路线的迁移文件并不多,只是基础知识。对于联接表:

"use strict";
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable("user_route", {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      userId: {
        type: Sequelize.INTEGER,
        onDelete: "CASCADE",
        references: {
          model: "Users",
          key: "id"
        }
      },
      routeId: {
        type: Sequelize.INTEGER,
        onDelete: "CASCADE",
        references: {
          model: "Routes",
          key: "id"
        }
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable("user_route");
  }
};

我的控制器和路线如下:

  create(req, res) {
    return UserRoutes.create({
      userId: req.body.userId,
      routeId: req.body.routeId
    })
      .then(userRoute => res.status(201).send(userRoute))
      .catch(err => res.status(400).send(err));
  },



app.post("/api/userRoutes", userRoutesController.create);

因此,当我尝试发布到该路线时,我会在帖子顶部收到错误消息。

2 个答案:

答案 0 :(得分:2)

我遇到了同样的错误,并且同样被一个不相关的问题抛出(我的SQL子句中的单引号都被转义了,并且由于查询是在删除它们时运行的,所以我专注于一种删除转义的方法)。我的问题是我的迁移使用的表名违反了PostgreSQL的命名约定。当我更正了这个错误(表名中的首字母大写,因此我编辑了小写首字母的迁移并重新运行)后,错误消失了。也许这可能会解决您的问题?

答案 1 :(得分:1)

创建数据库,模型和迁移后,需要运行

sequelize db:migrate

在运行应用程序之前。

如果没有,它将如上所述抛出 SequelizeDatabaseError