我正在尝试在 NodeJS 中使用 Sequelize 并使用他们的 Seeders CLI 尝试向 bulkInsert 命令添加查询。我创建了一个简单的 JS 函数,每次运行 sequelize 迁移命令时,它都会返回一个空值错误。我也尝试使用 beforeCreate 方法,但我不确定为什么错误说该函数不存在。这是我在代码中需要帮助的内容。
passGen.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'),
我想要做的是也许我需要添加一个 promise ?我该怎么做?
我认为会发生的是我的辅助函数将被调用,然后密码字段将具有 bcrypt 哈希值,但这并没有发生。在 CLI 中,我只是收到相同的“密码不接受空值”错误,因为在我的模型( Sequelize 迁移定义)字段中,null 为 false,因此它不能为 null。
如何使用我的辅助函数生成一个密码,该密码在我的种子文件中用于在 Sequelize 中创建一个帐户?
编辑:
如何在我的帐户模型 js 和帐户迁移 js 文件中实现这样的 Hook ,例如直接方法? sequelize hook docs
或者添加另一个像 Upsert 这样的 QueryInterface 怎么样?
Upsert Sequelize
最佳答案
似乎您需要文件本身,而不需要 Sequelize 。
您能否尝试更改此行:
const Accounts = require('../models/accounts');
至:
const model = require('../models/index');
然后将其用作:
model.Accounts.beforeCreate{(...
关于javascript - 如何使用带有 Promise 的 Sequelize 和自定义函数来播种数据文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49686284/