Search code examples
sql-serversequelize.jsnumeric

Convert NUMERIC to VARCHAR using sequelize model


I have this NUMERIC(20) field on mssql and I'm trying do read it as a data type string to get the full number because int limits on javascript

code: {
 type: DataTypes.STRING
}

But the returned value is a truncated INT

[ {code: 4216113112911594000 } ] 

No matter what kind of data type choose it'll return as truncated int

The original values is 4216113112911594192. This is a java UUID

How can a convert this value to using model.findAll()

This is a already created table for another application and I'm trying to read it using sequelize


Solution

  • Here you go :

    code: {
        type: Sequelize.INTEGER , // <------ keep is as DB's datatype
        get() { // <------ Use getter method to modify the output of query
            return this.getDataValue('code').toString();
        }
    }
    

    I think this might help you

    model.findOne({
        attributes: [[db.sequelize.literal('cast(`code` as varchar)'), 'code_string']] ,
        where : { id : YOUR_ID }
    }).then(data => {
        console.log(data); // <------ Check your output here
    })