为涉及 DataTypes.JSON 的 sequalize 创建种子文件时出错

Error in creating seed file for sequalize involving DataTypes.JSON

我正在为我的 Node.Js/PSQL 项目的 ORM 使用 Sequalize。我正在创建一个种子文件来预填充我的数据库;但是,当我 运行 种子文件时,我收到与以下相关信息的字段之一相关的错误。将 JSON 对象与

一起使用似乎存在问题

错误

== 20170308131757-examples: migrating =======
ERROR: Invalid value { example: 'mk@kWO5r' }

定义

 const example = sequelize.define('example', {
    date: DataTypes.DATE   
    data: {
      type: DataTypes.JSON,
      allowNull: true
    },    
  }, {});

种子文件

 up: function (queryInterface) {
    const examples = [];
    examples.push({
      date: new Date(),
      data: {
        data: dataFaker.string({ length: 8 })
      },
      createdAt: new Date(),
      updatedAt: new Date()
    });

    for(let i = 0; i < 20; i++) {
      testAlertLists.push({
        date: new Date(),
        data: {
          data: dataFaker.string({ length: 8 })
        },
        createdAt: new Date(),
        updatedAt: new Date()
      });
    }

    return queryInterface.bulkInsert('examples', examples, {});
  },

  down: function (queryInterface) {
    return queryInterface.bulkDelete('examples', null, {});
  }

我保留了相关的代码片段来简化事情,所以如果需要的话我可以添加更多的字段和其他方面,如果有与简化事情可能导致的错误无关的小拼写错误,我如果找到可以修复。

问题似乎是 Sequalize 不接受插入中的 JSON 对象,但它在代码和 table 中都被定义为 JSON 对象本身(我检查过)。我试过用几种不同的方式创建 Json 但除此之外我对这个问题有点困惑。在 psql 或 Sequalize 中使用 JSON 对象有问题吗?

因为 queryInterface 的级别有点低,所以您必须指定要插入 json,例如:

return queryInterface.bulkInsert('examples', examples, { data: { type: new Sequelize.JSON() } });

您可以作为 up 函数的第二个参数访问 Sequelize 对象。

此外,您可以使用示例模型中的 create 方法创建一条记录,而无需任何其他信息,例如:

example.create({
  date: new Date(),
        data: {
          data: dataFaker.string({ length: 8 })
        },
        createdAt: new Date(),
        updatedAt: new Date()
})

其中示例是定义的续集模型的实例

Sequelize CLI 存在与 JSON 类型相关的问题。我有同样的问题,并在 sequelize-cli 的 github 上找到了解决方案。如果我找到线程,我会更新源代码。你需要做的是使用 JSON.stringify() 因为它不会接受那个对象。

examples.push({
  date: new Date(),
  data: JSON.stringify({
    data: dataFaker.string({ length: 8 })
  }),
  createdAt: new Date(),
  updatedAt: new Date()
});