![](/img/trans.png)
[英]How to pass a seed value to random order function in Sequelize
[英]How To Seed Data Files Using Sequelize and Custom Function With Promise?
我正在尝试在NodeJS中使用Sequelize,并正在使用他们的Seeders CLI尝试将查询添加到bulkInsert命令。 我创建了一个简单的JS函数,每次运行sequelize migration命令时,它将返回一个空值错误。 我也尝试做一个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) => {
}
};
我也尝试添加密码字段来调用该函数,但仍然会导致返回null:
password: PassGenX.BpassGen('secretKey'),
我想做的是可能需要增加一个承诺? 我该怎么做? 我以为会发生什么事,那就是我的助手函数将被调用,然后密码字段将具有bcrypt哈希,但这并没有发生。 在CLI中,我会收到相同的错误消息:“密码不接受空值”,因为在我的模型(序列化迁移定义)中,null字段为false,因此它不能为null。
如何使用助手功能生成种子文件中用于在Sequelize中创建帐户的密码?
编辑:如何在我的Account模型js和Account迁移js文件中实现诸如直接方法之类的钩子? 序列化钩子文档
或如何添加另一个QueryInterface(如Upsert)?
似乎您需要文件本身,而不需要序列化。
您能否尝试更改此行:
const Accounts = require('../models/accounts');
至:
const model = require('../models/index');
然后将其用作:
model.Accounts.beforeCreate{(...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.