簡體   English   中英

如何使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM