使用 sequelize 将 JSON 数据播种到 PostgreSQL 数据库时出错

Error seeding JSON data with sequelize into PostgreSQL database

当我 运行 sequelize-cli 命令 sequelize db:seed:all

时发生

当我尝试将对象作为 JSON 播种时,出现以下错误:

ERROR: Invalid value { viewId: null,
  dateRanges: [ { startDate: null, endDate: null } ],
  samplingLevel: 'DEFAULT',
  dimensions: [ { name: 'ga:channelGrouping' } ],
  metrics: [ { expression: 'ga:users' } ] }

这是我的模型

module.exports = (Sequelize, DataTypes) => {
  const Report = Sequelize.define('Report', {
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        is: /^[a-z0-9\_\-]+$/i,
      },
    },
    platform: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        is: /^[a-z0-9\_\-]+$/i,
      },
    },
    query: {
      type: DataTypes.JSON,
    },
  });
  return Report;
};

这是我的种子文件

'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.bulkInsert('Reports', [
      {
        name: 'users per channel',
        platform: 'google',
        query: {
          "viewId": null,
          "dateRanges": [
            {
              "startDate": null,
              "endDate": null,
            },
          ],
          "samplingLevel": "DEFAULT",
          "dimensions": [
            {
              "name": "ga:channelGrouping",
            },
          ],
          "metrics": [{ "expression": "ga:users" }],
        },
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    ]);
  },

  down: (queryInterface, Sequelize) => {},
};

我能够使用此查询直接插入相同的数据

INSERT INTO "Reports" (id, name, platform, query, "createdAt", "updatedAt") VALUES (1, 'users per channel', 'google', '{"viewId":null,"dateRanges":[{"startDate":null,"endDate":null}],"samplingLevel":"DEFAULT","dimensions":[{"name":"ga:channelGrouping"}],"metrics":[{"expression":"ga:users"}]}', '2018-04-15 08:55:12.449-05', '2018-04-15 08:55:12.449-05');

我找不到和我有同样问题的人,所以我认为这很简单,但我看不到。

如果我将对象包装在 JSON.stringify() 中,我可以毫无问题地 运行 种子,但这肯定不是预期的。

遇到同样的问题 只需将 query 字段字符串化为

'{
   "viewId": null,
   "dateRanges": [
      {
         "startDate": null,
         "endDate": null,
      },
   ],
   "samplingLevel": "DEFAULT",
   "dimensions": [
        {
           "name": "ga:channelGrouping",
        },
    ],
   "metrics": [{ "expression": "ga:users" }],
}'

@Jaygles 看看你的sql

INSERT INTO "Reports" (id, name, platform, query, "createdAt", "updatedAt") VALUES (1, 'users per channel', 'google', '{"viewId":null,"dateRanges":[{"startDate":null,"endDate":null}],"samplingLevel":"DEFAULT","dimensions":[{"name":"ga:channelGrouping"}],"metrics":[{"expression":"ga:users"}]}', '2018-04-15 08:55:12.449-05', '2018-04-15 08:55:12.449-05');

您正在插入字符串化数据。所以你还需要在 seed

中对其进行字符串化