【问题标题】:How to save data in database at the time of creation using sequelize in node.js如何在创建时使用 node.js 中的 sequelize 将数据保存在数据库中
【发布时间】:2016-02-14 07:42:40
【问题描述】:

我正在尝试在创建数据库时保存批量数据。我的代码有以下问题:

  • 如果我保留 models.sequelize.sync({force: true}).then(function(){ }); 则表示未创建表。
  • 如果我保留 {force:false},那么在第一次部署中它会创建表,在第二次部署中它会将数据保存在数据库中。

模型/规范化.js

module.exports = function(sequelize, DataTypes) {
    var Speclization = sequelize.define("Speclization",
        {
            speclizationname: DataTypes.STRING
        }, {
            tableName: 'speclization', // this will define the table's name
            timestamps: false           // this will deactivate the timestamp columns
        }
    );

    Speclization.bulkCreate([
        {speclizationname: 'Computer Science'}, // part of records argument
        {speclizationname: 'Information Technology'},
        {speclizationname: 'Electrical'},
        {speclizationname: 'Other'},
        {speclizationname: 'Mechninncal'},
        {speclizationname: 'Electronics'}
    ], ['speclizationname'])
    return Speclization;
};

我无法弄清楚如何在数据库中的应用程序部署中保存数据的正确方法

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    如何从模型定义中删除 bulkCreate 并将其放入 sync 回调中? (因为表格将在 sync 之后创建,所以我认为您不能在 sync 完成之前 bulkCreate

    如下:

    models.sequelize.sync({force: true}).then(function(){
        Speclization.bulkCreate([
            {speclizationname: 'Computer Science'}, // part of records argument
            {speclizationname: 'Information Technology'},
            {speclizationname: 'Electrical'},
            {speclizationname: 'Other'},
            {speclizationname: 'Mechninncal'},
            {speclizationname: 'Electronics'}
        ]);
    });
    

    然后有这样的模型定义:

    module.exports = function(sequelize, DataTypes) {
        var Speclization = sequelize.define("Speclization",
            {
                speclizationname: DataTypes.STRING
            }, {
                tableName: 'speclization', // this will define the table's name
                timestamps: false           // this will deactivate the timestamp columns
            }
        );
        return Speclization;
    };
    

    顺便说一句,Speclization 应该写成英文的“Specialization”。 :)

    【讨论】:

    • 你能告诉我如何在每次部署时使用旧数据库重新创建数据库。因为如果我保留 {force: true} 则旧数据库将被删除并创建新数据库。
    • 我不确定你的意思,我认为它属于一个新问题:)
    • 是的,你是对的 :) 。我发布了一个新问题:stackoverflow.com/questions/35428355/…
    猜你喜欢
    • 2016-05-27
    • 1970-01-01
    • 2013-11-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 2013-01-30
    相关资源
    最近更新 更多