Skip to content

Instantly share code, notes, and snippets.

@fdevibe
Last active November 13, 2021 15:24
Show Gist options
  • Save fdevibe/dd50b091ea3a7c7eb8fa to your computer and use it in GitHub Desktop.
Save fdevibe/dd50b091ea3a7c7eb8fa to your computer and use it in GitHub Desktop.
Dumb, straightforward seeding Sequelize data. Feel free to improve. :-)
#! /usr/bin/env node
'use strict';
var db = require('./models'),
optimist = require('optimist'),
_ = require('lodash'),
path = require('path');
_.each(optimist.argv._, function (file) {
var module = require(path.join(process.cwd(), file));
module.seed(db.sequelize);
});
var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
csv = require('csv'),
Sequelize = require('sequelize');
function addUser(db, filename, rolesByName, addresses) {
var parser = csv.parse({}, function (err, data) {
db.models.User.bulkCreate(
_.map(data, function (record, index) {
// Create user attributes object and return it
})
);
fs.createReadStream(filename).pipe(parser);
}
var seed = function (db) {
Sequelize.Promise.all([
db.models.Role.findAll(),
db.models.Address.findAll()
]).spread(function (roles, addresses) {
var rolesByName = _.each(roles, function (role) {
rolesByName[role.name.toLowerCase()] = role;
});
addUsers(db, path.join(__dirname, 'data', 'users.csv'), rolesByName, addresses);
});
};
module.exports = {
seed: seed
};
@kazibo
Copy link

kazibo commented Oct 16, 2021

Thanks. I made this based on your code:

fs.createReadStream(path.join(__dirname, 'data', 'airports.csv')).pipe(csv.parse({}, function (err, data) {
        db.Airport.bulkCreate(
            _.map(data, function (record, index) {
                return {
                    'code': record[0],
                    'latitude': record[1],
                    'longitude': record[2]
                }
            })
        );
    }
));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment