SequelizeEagerLoadingError: There is no association between the model and the otherModel

I've come across this issue several times on various forums but haven't been able to resolve it yet. My setup involves Express and PostgreSQL with Sequelize ORM.

The problem lies in the one-to-one relationship between two models: Campus and Academic Manager. Each Campus is associated with one Academic Manager.

Although I have successfully implemented both models and their association, when attempting to fetch campus data with manager information included, I keep encountering the same error:

SequelizeEagerLoadingError: academic_manager is not associated to campus!

I suspect that the error may be related to the usage of include.

Below are snippets from my code:

campus.js

const campus = (sequelize, DataTypes) =>{
    const Campus = sequelize.define('campus', {
        name: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        manager: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'academic_manager',
                key: 'id'
            }
        } 
    });    

    Campus.associate = models => {
        Campus.hasOne(models.Manager, { foreignKey: 'id'});
    }

    return Campus; 
};

export default campus;

academic_manager.js

const manager = (sequelize, DataTypes) =>{
    const Manager = sequelize.define('academic_manager', {
        name: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        email: {
            type: DataTypes.STRING,
            allowNull: false
        } 
    });    

    Manager.associate = models => {
        Manager.belongsTo(models.Campus, { foreignKey: 'id'});
    }

    return Manager; 
};

export default manager;

And here's the get method:

router.get('/', async (req, res) => {
    const campus = await req.context.models.Campus.findAll({
        include: [
            { model: req.context.models.Manager }
        ]
    });
    return res.send(campus);
}); 

The get request works fine without the include. The association seems to be correctly set up as evidenced by the table descriptions:

TABLE "campus" CONSTRAINT "campus_manager_fkey" FOREIGN KEY (manager) REFERENCES academic_manager(id)

Answer №1

There are some issues with your model definition that could be confusing Sequelize regarding the association between models or just their references to each other.

You've included associations that implement relational constraints, but you've also added a reference key meant for referencing without implementing constraints.

I recommend reading:

  1. How to implement many to many association in sequelize
  2. https://sequelize.org/v5/manual/associations.html

I've provided comments on your code:

campus.js

const Campus = (sequelize, DataTypes) =>{
    const Campus = sequelize.define('Campus', {
        name: {
            type: DataTypes.STRING,
            allowNull: false,
        }
        // This is not correct.
        // Read further below when to use reference key
        /* manager: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'academic_manager',
                key: 'id' 
            }

        } */
    });    

    Campus.associate = models => {
        // Campus.hasOne(models.Manager, { foreignKey: 'id'});
        // The foreignKey `id` is incorrect. Your models already have `id` by default, which is their own.
        // You should either name it as `campus_id`, let sequelize handle it by not defining it and using `Campus.hasOne(models.Manager)`.
        // It's good practice to define it or else you'll need to figure out what sequelize named it for you later.
        // Read: https://sequelize.org/master/manual/assocs.html#providing-the-foreign-key-name-directly
        Campus.hasOne(models.Manager, { foreignKey: 'campus_id'); // Injects `campus_id` into `Manager`
    }

    return Campus; 
};

export default Campus;

academic_manager.js

const Manager = (sequelize, DataTypes) =>{
    const Manager = sequelize.define('Manager', {
        name: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        email: {
            type: DataTypes.STRING,
            allowNull: false
        }
    });    

    Manager.associate = models => {
        // Don't define the foreignKey here unless you want to inject it into `Campus`.
        Manager.belongsTo(models.Campus);
    }

    return Manager; 
};

export default Manager;

Additional Info - When to use this reference Key?

In relational databases, you should have only 1 path between any two models to prevent cyclic dependencies.

Imagine you have the third entity Location

Campus.hasOne(Manager)
Manager.belongsTo(Campus)

Location.hasOne(Campus)
Location.belongsTo(Campus)

Until if you decide that Manager will always stay in that Location, creating a circular reference.

To break this cycle, choose the most important relationship or avoid associating models altogether and use reference keys with manual joins or multiple queries.

Answer №2

The key to solving my issue was realizing that I had forgotten to link the associations in my models index. I overlooked this crucial step:

Object.keys(models).forEach(key => {
  if ('associate' in models[key]) {
    models[key].associate(models);
  }
});

It's important to remember to establish your associations properly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How Meteor Handles HTTP Requests in its package.js File

When accessing data from an external source at autopublish.meteor.com, our goal is to gather information about a package's latest release tag either from GitHub or the NPM registry: var version; try { var packageJson = JSON.parse(Npm.require(' ...

Is there an Atom package available for node.js similar to Emmet for providing autocomplete functionality?

Is there an Atom package available for autocompleting Node.js code like Emmet? ...

What is the best way to insert data from a promise into MongoDB?

While attempting to integrate an array of JSON data from a different server into a MongoDB collection, I encountered the following error message: "Cannot create property '_id' on string". Even though I am passing in an array, it seems to be causi ...

What functionalities does yarn offer that are not currently present in npm v5.0?

With the release of npm v5.0, many features currently found in yarn are now included: The default installation includes --save. package-lock.json will be generated automatically (assumed to ensure consistent installs). Automatic fallback-to-offline mode. ...

javascript string assignment

Is it possible to conditionally assign a string based on the result of a certain condition, but for some reason, it's not working? var message = ""; if (true) { message += "true"; } else { message += "false" } console.log(message); ...

Mongoose: Mastering Error Management

I'm currently creating an API using Restify and Mongoose, tools that I have recently started exploring. Unfortunately, I am facing difficulties in properly handling errors within the Mongoose / Node framework. Presently, I am attempting to handle err ...

The issue of "command not found: webpack-dev-server" arises when encountering errors with webpack-dev-server

Having trouble getting this to run... Here's what I've done: npm install -g webpack webpack-dev-server Verified that both installations were successful. However, when attempting to execute webpack-dev-server, I encounter the following error: ...

Can I find a better approach to optimize this code?

How can I refactor this code to move the entire DB query logic into a separate file and only call the function in this current file? passport.use( new GoogleStrategy({ clientID: googleId, clientSecret: clientSecret, callbackURL: ...

Managing Sessions, Node and Express, and Schema Objects in Mongoose

Currently, I have been exploring Node.js along with Express and Mongoose for my project. My Mongoose Schema is utilized to store session data, while 'connect-mongodb' is used for session management using the native driver. The realization dawned ...

Command your way through NodeJS with Node Space Dot!

After a hiatus, I returned to my Node JS script in my development directory filled with various test JS scripts. I loaded a script that seemed to be the one I wanted based on its name and most recent date. Using the command: C:\testscripts>node . ...

Investigating TLS client connections with node.js for troubleshooting purposes

I am currently facing an issue while setting up a client connection to a server using node.js and TLS. My query revolves around how I can gather more information regarding the reason behind the connection failure. It would be great if there is a way to ob ...

Updating the _id of a Mongoose document upon save or update

Just a quick question: I noticed that when I push an update, Mongoose is changing/upgrading the _id field of a document. Is this behavior intentional? Thank you. Here's the update code I'm using in my PUT route. It successfully returns the upd ...

My NestJS Docker container application is running smoothly, but every time I redeploy it on the server, the uploads folder gets deleted

I'm facing an issue with my NestJS Docker container app. It runs smoothly, but every time I deploy it on the server, the uploads folder gets removed. I attempted to solve this by using Docker volume, but unfortunately, it didn't work out as expe ...

I am looking to upsert documents in mongoose by inserting them

Currently, I'm pulling data from an external API and my goal is to add multiple records if they don't already exist. The array of objects that I've created looks like this: data=[ { match_id: 212167781, player1Id: 129753806, pl ...

Having trouble with nodeJS when running the command "npm install"?

Can anyone help me understand why I'm encountering issues when running "npm install"? Whenever I run npm install, I am bombarded with numerous errors. npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs&bsol ...

What is the process for setting up URL parameters in Express JS?

I am working on creating an URL that can accept a query after the "?" operator. The desired format for the URL is "/search?q=". I am wondering how I can achieve this in Express JS, and also how I can integrate the "&" operator into it. ...

Trouble with Firebase Setup in Ionic 4+ Web Application

I'm currently trying to establish a connection between my ionic application and Firebase for data storage, retrieval, and authentication. Despite using the npm package with npm install firebase, I encountered an error message that reads: > [email& ...

What is the best way to ensure my npm package on GitHub is up to

Is there a way to update npm packages on GitHub when the version dependencies are outdated? I do not own these packages, but my platform relies on them. When I update my Node.js version to the latest one, I encounter errors. Below are the commands I have ...

Error: CORS issue with Express, Angular, and Browsersync - `Access-Control-Allow-Origin'` is not allowed causing a 403 (forbidden) error

I'm completely new to web development and I need help with accessing data from the USDA Food Composition Databases NDB API - while making an angular $http request from localhost. I am using an express server and gulp/browsersync, but I am facing two ...

Encountering an error while attempting to generate a fresh Ionic 3 project. npm reports the following issue: "npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] postinstall

Today has been a rough day as I attempt to start a new project in Ionic 3. The versions of software I am using are as follows: Ionic 3.9.2 npm 6.7.0 node v8.10.0 Operating on Ubuntu 18, each time I run the following command: sudo ionic start test blank ...