Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
How to let defaultValue in Sequelize migaration file take values from some column?

I am adding a new column "companyCode" to an existing table "company", and it shouldn't be null. The value of this column will vary from one raw to another as it takes the first three letters of the company's name (there is a column "name" includes company's name), I tried using Sequelize.litereal('//a query within') and read from "name" column but it did not accept it, So I am trying to let default value takes a function, but still does not work, is there another way to solve this issue? here is my code:

'use strict';

module.exports = {
    up: (queryInterface, Sequelize) => {
        return queryInterface
            .addColumn('company', 'companyCode', {
                type: Sequelize.STRING(3),
                allowNull: false,
                defaultValue:  Sequelize.fn(() => {
                    let query = 'SELECT name FROM company';
                    return queryInterface.sequelize.query(query, {type: Sequelize.QueryTypes.SELECT})
                        .then(companies => {
                            console.log(companies);
                            return companies.map(company => {
                                return {
                                    companyCode: company.name.slice(0, 3).toUpperCase(),
                                };
                            });
                        })
                        .then(data => {
                            if (!data.length) return;
                            return queryInterface.bulkInsert('company', data);
                        });
                }),
            
            });
    },

    down: (queryInterface) => {
        return queryInterface.removeColumn('company', 'companyCode');
    }
};```
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I would create all of it and then run a script to insert inside the problem that might be from the async way of working.

about 4 years ago · Juan Pablo Isaza Relatório

0

After trying many times, It could be solved with a promise that holds a query as following:


module.exports = {
    up: async (queryInterface, Sequelize) => {
        await queryInterface.addColumn(
            'company',
            'companyCode',
            {
                defaultValue: '',
                allowNull: false,
                type: Sequelize.STRING(3)
            }
        ).then(function (result) {
                return queryInterface.sequelize.query('UPDATE company SET "companyCode"=LEFT("name",3)');
            }
            );  

    },
    down: async (queryInterface, Sequelize) => {
        await queryInterface.removeColumn('company', 'companyCode');
    }
};```
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda