Better Programming

Advice for programmers.

Follow publication

Cross-Database Associations in Sequelize ORM

Don’t create two or more separate queries when it’s possible to use one

David Mart
Better Programming
Published in
2 min readJun 11, 2019

--

I’ve been using Sequelize for years now and it’s been a great tool for me. I implemented huge amounts of very large and complex queries using scopes and associations.

At some point, I think I pretty much became a pro at it and was able to do absolutely anything that was required, except one thing — cross-database joints.

It was a huge struggle for me as some of the applications used multiple databases and some queries required to get associated data from several of them. There are a lot of topics on Stack Overflow and GitHub Issues, but none of them had exact steps to make it work.

For a long time, I had to write queries manually, executing them with sequelize.query.

It’s been working fine for me, especially combining them with model hooks, but it’s always bothered me having to make two or more separate queries, when it’s possible to use one.

Let’s look at some code. Let’s say, we have two databases: one containing users and orders, another one containing products. Users can have multiple orders and orders can have multiple products:

Model definitions:

Let’s create two Sequelize database connection instances:

And set up some associations:

Now, we can use autogenerated model methods to create and view products that belong to a specific order:

However, if we are going to try to use the include option, we’re going to hit the following error

Let’s go ahead and fix that.

The first thing you need to do is to manually adjust the Sequelize database connection instance, like so:

Then, add the schema name to the product model options:

Lastly, you need to manually update the association scope, as the default association is still going to try to hit the users_and_orders.

Bingo! Now you can create multiple complex queries using tables from different databases.

Deeper Nesting

Make sure you use the literal string representation if you want to do deeper nesting, like so:

Happy hacking!

--

--

David Mart
David Mart

Written by David Mart

Senior Google Cloud Engineer at SADA Systems

Responses (8)

Write a response