Thursday, 29 April 2021

How do I update a foreign key (belongsTo) in Sequelize

I have the following model:

'use strict';
const {Model} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Key extends Model {
    static associate(models) {
      Key.belongsTo(models.User, {
        foreignKey: 'userId',
        onDelete: 'CASCADE'
      });
    }
  };
  Key.init({
    keyType: DataTypes.STRING,
    key: DataTypes.JSON
  }, {
    sequelize,
    modelName: 'Key',
  });
  return Key;
};

I then try to create a row, after receiving userId, keyType and key:

...
const Key = KeyModel(sequelize, Sequelize);
const createKey = async (userid, keyType, key) => {
  const result = await Key.create({userId, keyType, key});
  return result;
}

The row gets created successfully in the DB, and i get back an ID (the createdAt and updatedAt are updated as well), but the userId is null.

How should I pass it to the create method so the value gets to the DB? Am I missing something in the model?

PS: the DB is MySQL 8.



from How do I update a foreign key (belongsTo) in Sequelize

No comments:

Post a Comment