【问题标题】:Scalable seeding for Sequelize with Node.js?使用 Node.js 进行 Sequelize 的可扩展播种?
【发布时间】:2017-11-16 09:07:43
【问题描述】:

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

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

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

【问题讨论】:

    标签: node.js promise sequelize.js seed seeding


    【解决方案1】:

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

    当我需要一个直接返回 Promise 的文件时,立即调用了 Promise。
    我通过返回返回 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时想到了这个

    【讨论】:

      猜你喜欢
      • 2018-08-08
      • 1970-01-01
      • 2016-08-25
      • 2018-03-05
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      相关资源
      最近更新 更多