node.js - 使用 Node.js 进行 Sequelize 的可扩展播种?

标签 node.js promise sequelize.js seed seeding

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

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

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

最佳答案

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

当我需要一个直接返回一个 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 时想到了这个

关于node.js - 使用 Node.js 进行 Sequelize 的可扩展播种?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47325531/

相关文章:

javascript Promise 解析函数与解析匿名函数

javascript - promise 和周期

sql - 从 Sequelize 原始 SQL 查询返回大写列名

node.js - 如何使用expressjs在React中上传图像

javascript - Sails.js 中的多个关联

javascript - 指示本地模拟的 Firebase 函数使用身份验证模拟器

node.js - 为什么ZeroMQ消息会被扰乱?

javascript - 为什么这个node-mysql插入会产生一个数组?

javascript - 使用 MariaDB、Sequelize 和 Node.js 获取数百万条记录以显示在 DevExtreme PivotGrid 中

node.js - 什么导致 AWS Lambda 上的 Mongodb 超时错误?