NodeJS Sequelize-CLI播种器-无法读取未定义的属性

z0qdvdin  于 2023-08-04  发布在  Node.js
关注(0)|答案(3)|浏览(104)

我已经在X1 M0 N1 X上挣扎了一个多小时了,慢慢地我对此失去了理智。
我有一个简单的模型:

'use strict';
module.exports = function (sequelize, DataTypes) {
  var Car = sequelize.define('Cars', {
    name: DataTypes.STRING,
    type: DataTypes.INTEGER,
    models: DataTypes.INTEGER
  }, {
      classMethods: {
        associate: function (models) {
          // associations can be defined here
        }
      }
    });
  return Car;
};

字符串
这是在迁移中,并使用工作正常的sequelize db:migrate转到数据库。
接下来我想插入-通过一个种子文件- 2辆汽车。因此,我运行命令sequelize seed:create --name insertCars并添加bulkInsert

'use strict';

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.bulkInsert(
      'Cars',
      [
        {
          name: "Auris",
          type: 1,
          models: 500,
          createdAt: Date.now(), updatedAt: Date.now()
        },
        {
          name: "Yaris",
          type: 1,
          models: 500,
          createdAt: Date.now(), updatedAt: Date.now()
        }
      ]
    );
  },

  down: function (queryInterface, Sequelize) {
  }
};


现在,当我运行sequelize db:seed:all时,我得到以下错误:

Loaded configuration file "config\config.json".
Using environment "development".
== 20160510132128-insertCars: migrating =======
Seed file failed with error: Cannot read property 'name' of undefined


有没有人有任何经验与运行这些播种机?以下是我的配置文件:

{
  "development": {
    "username": "mydbdude",
    "password": "mydbdude",
    "database": "Cars",
    "host": "127.0.0.1",
    "dialect": "mssql",
    "development": {
      "autoMigrateOldSchema": true
    }
  },
  ....other configs
}

EDIT:db:migrate输出

Sequelize [Node: 5.9.1, CLI: 2.4.0, ORM: 3.23.0]

Loaded configuration file "config\config.json".
Using environment "development".
No migrations were executed, database schema was already up to date.

pbossiut

pbossiut1#

由于我仍然没有能够得到这个工作,我,现在,然后,张贴我的解决方案,我用它的工作相当不错,但定制的。
首先,我创建了一个JSON文件,其中包含我想要播种的对象。即

dataSources: [
    {
        name: 'Pattern'
    },
    {
        name: 'Upload'
    }
]

字符串
接下来,我在应用程序的服务器端实现了一个seeder.js,包含以下内容(当然是精简版)

var models = require('./../models'),
sql = models.sequelize,
Promise = models.Sequelize.Promise;

var objects = require('./seed/objects'), //this is where my object file is
dataSources = objects.dataSources;

var express = require('express');

var seedDatabase = function () {
    var promises = [];
    promises.push(createDataSources());
    //more can be added to the promises

    return Promise.all(promises);
};

function createDataSources() {
    return models.sequelize
        .transaction(
            {
                isolationLevel: models.sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED
            },
            function (t) {
                return models.DataSource
                    .findAll({
                        attributes: [
                            'id'
                        ]
                    })
                    .then(function (result) {
                        if (!result || result.length == 0) {
                            return models.DataSource
                                .bulkCreate(dataSources, { transaction: t })
                                .then(function () {
                                    console.log("DataSources created");
                                })
                        }
                        else {
                            console.log("DataSources seeder skipped, already objects in the database...");
                            return;
                        }
                    });
            })
        .then(function (result) {
            console.log("DataSources seeder finished...");
            return;
        })
        .catch(function (error) {
            console.log("DataSources seeder exited with error: " + error.message);
            return;
        });
};

module.exports = {
    seedDatabase: seedDatabase
}


现在所有这些设置都完成了,我可以在应用程序启动时使用这个seedDatabase函数来运行我的seeder,如下所示:

//includes and routes above, not interesting for this answer
try {
    umzug.up().then(function (migrations) {
        for (var i = 0; i < migrations.length; i++) {
            console.log("Migration executed: " + migrations[i].file);
        }

        console.log("Running seeder");
        seeder.seedDatabase().then(function () { //here I run my seeders
            app.listen(app.get('port'), function () {
                console.log('Express server listening on port ' + app.get('port'));
            });
        });
    });
}
catch (e) {
    console.error(e);
}


就是这样,现在,当你运行你的应用程序时,seeder将检查数据库,如果你的任何对象已经插入到数据库中。如果是,则跳过播种器,如果不是,则插入它们。
我希望这对你们有帮助。

xsuvu9jc

xsuvu9jc2#

我也有同样的问题,问题是我在对象之间添加了额外的逗号,检查任何可能工作的语法错误

dataSources: [
    {
        name: 'Pattern'
    },
    ,// this comma was added by mistake for me
    {
        name: 'Upload'
    }
 ]

字符串

yc0p9oo0

yc0p9oo03#

我在这里结束是因为我在bulkInsert的选项中包含了updateOnDuplicate。这个选项似乎是要与另一个名为“upsertKeys”的字段配对。这两个属性应该是数组,表示执行批量插入的表的列,例如:

queryInterface.bulkInsert(
  "table_name",
  mapDataAndAddCreatedAndUpdatedAtField(array_of_db_entries),
  {
    transaction,
    ignoreDuplicates: false,
    updateOnDuplicate: ["col1", "col2", ..., "coln"],
    upsertKeys: ["unique_col1", ..., "unique_coln"],
  }
);

字符串

相关问题