1
votes

I have a pre-existing data in the form of JSON files which I am trying to insert into Sequelize SQLite table. I have 2 tables: Master_Vessel and Requests. There is a Request.hasOne(Vessel) association, meaning that every request has a vessel associated with it.

The key connecting both the models is vessel.Vessel_Name, which is a string. The data has been generated from a system which validates the keys so it is consistent (every request.Vessel_Name exists in vessel.Vessel_Name, vessel.Vessel_Name is unique).

I want to load this data into Sequelize managed table. I am creating the models as follows:

var Request = sequelize.define('request', {
     // other fields
     Vessel_Name: {
        type: Sequelize.STRING
     }
}, {
    tableName: 'Request'
});

var Vessel = sequelize.define('vessel', {
     // other fields
     Vessel_Name: {
        type: Sequelize.STRING,
        primaryKey: true
     }
}, {
    tableName: 'Master_Vessel'
});

And, the association is as follows:

Request.hasOne(Vessel, {foreignKey: 'Vessel_Name', allowNull: true});

Now, I am loading the data in following steps:

  1. Create and bulk load the Vessel model
  2. Create the Request model, the association and bulk load the Request model

Everything runs fine without any issues. However when I try to query using the association as follows:

Request.findOne()
.then(request => {
    console.log(request.get())
    request.getVessel()
    .then(vessel => console.log(vessel))
});

request instance contains the Vessel_Name foreign key, however the vessel instance is null.

Can anybody please help?

1

1 Answers

1
votes

Okay this is happenning because I got the Sequelize 'vocabulary' mixed up, Request.hasOne(Vessel) does NOT mean Request will have one Vessel_Name that will point to a Vessel. It is to be read R->L for correct meaning, not L->R.

The solution to the problem was changing the association from hasOne to belongsTo as follows: Request.belongsTo(Vessel), so now the FK will be created on Request.

Quite a confusing choice of association names and semantics!