I am using sequelize ORM 6.4.0 and CLI 6.2.0 in an express/nuxt web app. (Also: Node 14.15.3, npm 6.14.11).
Background: Goal is to make a web app for creating mariokart tournaments and track data about individual racers performance on different tracks, vehicles, etc. Issue is around postgres/sequelize associations and creating/using them correctly.
I'm trying to create a "racer" model that has a default vehicle which is from the Vehicle table. I'm using postgres for my tables and am having no trouble creating or interacting with my tables using express and sequelize for the API.
Here is my racer.js model:
'use strict'
const {
Model
} = require('sequelize')
module.exports = (sequelize, DataTypes) => {
class Racer 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) {
// define association here
this.belongsTo(models.Vehicle, {
foreignKey: 'vehicleName',
as: 'defaultVehicle'
})
}
};
Racer.init({
name: DataTypes.STRING,
nickname: DataTypes.STRING
}, {
sequelize,
modelName: 'Racer'
})
return Racer
}
My vehicle.js model:
'use strict'
const {
Model
} = require('sequelize')
module.exports = (sequelize, DataTypes) => {
class Vehicle 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) {
// define association here
this.hasMany(models.Racer)
}
};
Vehicle.init({
vehicleName: DataTypes.STRING,
vehicleSize: DataTypes.STRING,
vehicleClass: DataTypes.STRING,
vehicleClass2: DataTypes.STRING,
vehicleSpeed: DataTypes.INTEGER,
vehicleWeight: DataTypes.INTEGER,
vehicleAcceleration: DataTypes.INTEGER,
vehicleHandling: DataTypes.INTEGER,
vehicleDrift: DataTypes.INTEGER,
vehicleOffroad: DataTypes.INTEGER,
vehicleMiniturbo: DataTypes.INTEGER
}, {
sequelize,
modelName: 'Vechile'
})
return Vehicle
}
When I view my tables in pgadmin I don't see a defaultVehicle column and if I try to seed the value I thrown "ERROR: column "defaultVehicle" of relation "Racers" does not exist"
I've tried messing around with the names in case it was a capitalization/pluralization thing but that doesn't seem to be the case. I'm struggling to find any documentation that helps, most sequelize docs are using the old .define syntax (I'm trying this primarily because this is the skeleton that gets generated when I use the CLI and it seems like best practices moving forward). What am I missing? Thanks in advance if you can help I'm going crazy and about to just skip the table associations all together and pull all the data then code validations manually.