1

I have a simple model, with an _id column as expected, but there is a secondary id which I would like to default to the same value of the _id column. This is currently what the model looks like:

const sequelize = app.get('sequelize')

sequelize.define('myTable', {
  _id: {
    type: Sequelize.INTEGER,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true
  },
  otherId: {
    type: Sequelize.TEXT,
    allowNull: false
  }
  someField: {
    type: Sequelize.TEXT,
    allowNull: false
  }
})

So if I don't pass in a value for otherId when I am inserting a new row, I'd like it to be the same value as _id can this be done? If so, how can I achieve that?

theJuls
  • 6,788
  • 14
  • 73
  • 160

2 Answers2

3

You just need to inform Sequelize to default from another column:

otherId: {
    type: Sequelize.TEXT,
    allowNull: false,
    defaultValue: Sequelize.col('_id')
}
bad_coder
  • 11,289
  • 20
  • 44
  • 72
KenOn10
  • 1,743
  • 1
  • 9
  • 10
0

maybe this is not what you are looking for, but hopefully it can be of help for reference

model

class ModelPengguna extends Model{}
ModelPengguna.init({
    user_id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV1
    },
    name: {
        type: DataTypes.VIRTUAL,
        get(){
            return `/${this.id}/${this.user_id}`
        }
    }
},{sequelize})

contoller

const lihat = await pengguna.findAll();
console.log(JSON.stringify(lihat, null, 2))

result

[
  {
    "name": "/1/ae0c6760-3c54-11eb-80ed-59fb8d2c0509",
    "id": 1,
    "user_id": "ae0c6760-3c54-11eb-80ed-59fb8d2c0509",
    "createdAt": "2020-12-12T08:33:15.991Z",
    "updatedAt": "2020-12-12T08:33:15.991Z"
  }
]
malik kurosaki
  • 1,747
  • 15
  • 9