Node.js 的 Sequelize 的可扩展播种?

Scalable seeding for Sequelize with Node.js?

我想设置一段代码来重置我的整个数据库并播种所有内容。

问题在于,由于有一些外键约束,种子需要按顺序发生,但是那些不依赖的种子应该异步同时发生。

如何在单独的文件中正确定义这些种子?

问题归结为使用 module.exports 导出 Promise。

当我需要一个直接 returned Promise 的文件时,Promise 会立即被调用。
我通过 returning return Promise 的函数解决了这个问题。

Resetting DB and seeding

const Seed = require('../seeds/index');

sequelize.sync({ force: true }).then(() => {
    return Seed();
}).then(() => {
    // DB reset
}).catch(err => {
    // Error in one of the seeds, specific error in 'err'
});


seeds/index.js - 在其他文件中调用种子

const UserSeed = require('./user');
const BComponentSeed = require('./bcomponent');
const MaterialSeed = require('./material');

module.exports = function() {
    return Promise.all([ // Returning and thus passing a Promise here
        // Independent seeds first
        UserSeed(),
        BComponentSeed(),
        MaterialSeed(),
    ]).then(() => {
        // More seeds that require IDs from the seeds above
    }).then(() => {
        console.log('********** Successfully seeded db **********');
    });
}


seeds/user.js - 用户种子示例

const User = require('../models/user');
const crypto = require('../globs/crypto');

module.exports = function() {
    return User.bulkCreate([ // Returning and thus passing a Promise here
        {
            email: 'John@doe.com',
            password: crypto.generateHash('john'),
        },
        {
            email: 'a@a.com',
            password: crypto.generateHash('a'),
        },
    ]);
};


在回复 this GitHub issue

时想到了这个