如何使用续集和自定义功能与承诺一起播种数据文件?



我正在尝试在 NodeJS 中使用 Sequelize,并使用他们的播种器 CLI 尝试将查询添加到 bulkInsert 命令。我创建了一个简单的 JS 函数,每次运行续集迁移命令时,它都会返回一个空值错误。我也尝试做一个 beforeCreate 方法,但我不确定为什么错误说该函数不存在。这是我在代码中需要帮助的内容。

传代.js

const bcrypt = require('bcrypt');
// https://github.com/kelektiv/node.bcrypt.js
function BpassGen(password){
bcrypt.hash(password, 15, function(err, hash) {
return hash;
});
}
exports.BpassGen = BpassGen;

然后我的种子文件

'use strict';
const PassGenX = require('../helpers/passwordGeneration');
var sequelize = require('sequelize');
const uuidV1 = require('uuid/v1');
const Accounts = require('../models/accounts');
const uuidT = uuidV1();
var password = PassGenX.BpassGen('secretConfig');
module.exports = {
up: (queryInterface, Sequelize) => {
// ERROR: Accounts.beforeCreate is not a function
Accounts.beforeCreate((Accounts, options) => {
return PassGenX.BpassGen('secretConfig').then(hashedPw => {
Accounts.password = hashedPw;
});
});
return queryInterface.bulkInsert('Accounts', [
{
uid: uuidT,
userName: 'NaniMae1',
firstName: 'Nani',
lastName: 'Mae',
dateOfBirth: new Date(),
email: 'yaya@gmail.com',
backupEmail: 'dsf@gmail.com',
phoneNumber: null,
phoneNumberStatus: 1,
twoFactorEnabled: 1,
imageURL: null,
passwordHash: '',
passwordKey: '',
securityStamp: '',
userLimit: 10,
createdAt: new Date(),
updatedAt: new Date(),
Id_dataValidity: 1,
Id_status: 1,
Id_accountRole: 1,
Id_inviteKey: 1,
Id_privacy: 2
}
], {});
},
down: (queryInterface, Sequelize) => {
}
};

我还尝试添加密码字段来调用函数,但它仍然导致空:

password: PassGenX.BpassGen('secretKey'),

我想做的是也许我需要添加一个承诺?我该怎么做? 我认为会发生的是我的帮助程序函数将被调用,然后密码字段将具有 bcrypt 哈希,但这并没有发生。在 CLI 中,我只是收到相同的错误"密码不接受空值",因为在我的模型(续集迁移定义)中,null 的字段为 false,因此它不能为空。

如何使用我的辅助函数生成一个密码,该密码在我的播种器文件中用于在 Sequelize 中创建帐户?

编辑: 如何将这样的钩子(例如直接方法)实现到我的帐户模型 js 和帐户迁移 js 文件中?续集钩子文档

或者添加另一个像 Upsert 这样的 QueryInterface 怎么样?

更新插入续集

似乎您需要文件本身,没有续集。

您能否尝试更改此行:

const Accounts = require('../models/accounts');

自:

const model = require('../models/index');

然后将其用作:

model.Accounts.beforeCreate{(...