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

David Mart
Jun 11 · 2 min read

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!

Better Programming

Advice for programmers.

David Mart

Written by

Senior Google Cloud Engineer at SADA Systems

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade