I am facing an issue in defining the relationship between models in the Nodejs express app. I have two models one is Contact and the other is Conversation, I want to define a one-to-one relationship between them. Contact hasOne Conversation and Conversation belongsTo Contact. I am using Sequelize as ORM.
Nodejs version - v14.15.1(Using ECMAScript ) Sequelize - 6.5.0
Contact Model
import sequelize from "sequelize";
import database from "../config/database.js";
import Conversation from "./conversation.js";
const { DataTypes } = sequelize;
const Contact = database.define("contact", {
opted_in: {
default: false,
type: DataTypes.BOOLEAN,
},
uuid: {
type: DataTypes.STRING,
},
country_code: {
type: DataTypes.STRING,
allowNull: false,
},
mobile_number: {
type: DataTypes.STRING,
allowNull: false,
},
name: {
type: DataTypes.STRING,
},
email: {
type: DataTypes.STRING,
isEmail: true,
},
});
Contact.hasOne(Conversation);
export default Contact;
Conversation Model
import sequelize from "sequelize";
import database from "../config/database.js";
import Contact from "./contact.js";
const { DataTypes } = sequelize;
const Conversation = database.define("conversation", {
uuid: {
type: DataTypes.STRING,
},
last_message_created_at: {
type: DataTypes.DATE,
},
last_inbound_message_created_at: {
type: DataTypes.DATE,
},
unread_messages_count: {
type: DataTypes.INTEGER,
},
status: {
type: DataTypes.INTEGER,
// values: ['unattended', 'attended', 'inprocess'],
default: 1,
},
});
Conversation.belongsTo(models.Contact, {
allowNull: false,
foreignKey: {
name: "uni_contact_id",
},
as: "unilodgers",
});
export default Conversation;
On starting my application I am getting the below error -
Contact.hasOne(Conversation); ^
ReferenceError: Cannot access 'Conversation' before initialization