I'm working in insomnia trying to create a new account entry.
I'm getting the following line in terminal. At the end you can see that accountId
column is returned and I don't need it.
Executing (default): INSERT INTO "accounts" ("id","name","userId","type","limit","balance","createdAt","updatedAt") VALUES (DEFAULT,$1,$2,$3,$4,$5,$6,$7) RETURNING "id","name","userId","type","limit","balance","minPayment","dueDate","createdAt","updatedAt","accountId";
Because of it I get this error in insomnia:
column "accountId" does not exist
Below is the Account model
'use strict'
const { Model } = require('sequelize')
module.exports = (sequelize, DataTypes) => {
class Account extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
Account.hasMany(models.Transaction, { foreignKey: 'accountId' })
Account.belongsTo(models.User, { foreignKey: 'userId' })
}
}
Account.init(
{
name: {
type: DataTypes.STRING,
allowNull: false
},
userId: {
type: DataTypes.INTEGER,
onDelete: 'CASCADE',
references: {
model: 'users',
key: 'id'
}
},
type: {
type: DataTypes.INTEGER,
allowNull: false
},
limit: {
type: DataTypes.INTEGER,
allowNull: false
},
balance: {
type: DataTypes.INTEGER,
allowNull: false
},
minPayment: DataTypes.INTEGER,
dueDate: DataTypes.DATE
},
{
sequelize,
modelName: 'Account',
tableName: 'accounts'
}
)
return Account
}
Below is the User Model
'use strict'
const { Model } = require('sequelize')
module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
User.hasMany(models.Account, { foreignKey: 'accountId' })
}
}
User.init(
{
firstName: {
type: DataTypes.STRING,
allowNull: false
},
middleName: DataTypes.STRING,
lastName: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
}
},
{
sequelize,
modelName: 'User',
tableName: 'users'
}
)
return User
}
I've tried updating my Account model trying to remove the foreign key accountId
CodePudding user response:
You made a mistake in the User's association: You wrote:
User.hasMany(models.Account, { foreignKey: 'accountId' })
The correct one:
User.hasMany(models.Account, { foreignKey: 'userId' })