如何使用Sequelize和自定义功能与承诺种子数据文件?

时间:2018-04-06 05:56:21

标签: javascript node.js sequelize.js bcrypt

我正在尝试在NodeJS中使用Sequelize并使用他们的Seeders CLI尝试向bulkInsert命令添加查询。我创建了一个简单的JS函数,每次运行sequelize migration命令时都会返回null值错误。我也试过做一个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中,我只得到“密码不接受空值”的相同错误,因为在我的模型(sequelize migration definition)中,null为false,因此它不能为空。

如何使用我的助手功能生成我的播种器文件中用于在Sequelize中创建帐户的密码?

编辑: 我如何实现这样的钩子,如直接方法到我的帐户模型js和帐户迁移js文件? sequelize hook docs

或者如何添加另一个像Upsert一样的QueryInterface?

Upsert Sequelize

1 个答案:

答案 0 :(得分:1)

似乎你需要文件本身,没有sequelize。

请你试着改变这一行:

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

为:

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

然后将其用作:

model.Accounts.beforeCreate{(...