Sequelize-CLI Seeders - Cannot read property of undefined
Since I still have not been able to get this working, I, now then, post my solution I used which works rather well but is custom built.
First, I have created a JSON file containing the object I want to seed. i.e.
dataSources: [
{
name: 'Pattern'
},
{
name: 'Upload'
}
]
Next, I have implemented a seeder.js
in the server side of my application containing the following (trimmed version of course)
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
}
Now all this setup is done, I can use this seedDatabase
function when my application starts in order to run my seeder, like so:
//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);
}
That's it, now, when you run your application, the seeder will check the database if any of your objects are already inserted in the database. If so, the seeder is skipped, if not, they are inserted.
I hope this will help you guys.