Javascript 如何使用Sequelize和Promise自定义函数为数据文件种子?
我尝试在NodeJS中使用Sequelize,并使用他们的Seeders CLI尝试向bulkInsert命令添加查询。我创建了一个简单的JS函数,每次运行sequelize迁移命令时,它都会返回一个空值错误。我还尝试过使用beforeCreate方法,但我不确定为什么错误会说该函数不存在。下面是我需要的代码帮助 passGen.jsJavascript 如何使用Sequelize和Promise自定义函数为数据文件种子?,javascript,node.js,sequelize.js,bcrypt,Javascript,Node.js,Sequelize.js,Bcrypt,我尝试在NodeJS中使用Sequelize,并使用他们的Seeders CLI尝试向bulkInsert命令添加查询。我创建了一个简单的JS函数,每次运行sequelize迁移命令时,它都会返回一个空值错误。我还尝试过使用beforeCreate方法,但我不确定为什么错误会说该函数不存在。下面是我需要的代码帮助 passGen.js const bcrypt = require('bcrypt'); // https://github.com/kelektiv/node.bcrypt.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字段来调用函数,但结果仍然为null:
password: PassGenX.BpassGen('secretKey'),
我想做的是也许我需要补充一个承诺?我该怎么做?
我认为会发生的是,我的helper函数将被调用,然后密码字段将有bcrypt散列,但这并没有发生。在CLI中,我刚刚得到相同的错误“password不接受null值”,因为在我的models(sequelize迁移定义)中,null字段为false,因此它不能为null
如何使用my helper函数生成在Sequelize中创建帐户的种子文件中使用的密码
编辑:
如何在我的帐户模型js和帐户迁移js文件中实现像这样的钩子(如direct方法)
或者添加另一个查询接口,比如Upsert
看来您需要的是文件本身,而不是续集 你能试着换一下这行吗
const Accounts = require('../models/accounts');
致:
然后将其用作:
model.Accounts.beforeCreate{(...
您好,如果我在bulkInsert方法中提供密码字段,是否将其留空?我应用了你的建议并得到:错误:“密码”列中的空值违反了非空约束。你可以再次查看我的帖子吗?我添加了一个编辑,其中包含一些新的建议。
model.Accounts.beforeCreate{(...