2022-10-05
4597
#node
Thomas Hunter II
259
Oct 5, 2022 ⋅ 16 min read

Node.js ORMs: Why you shouldn’t use them

Thomas Hunter II Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript, is the author of Distributed Systems with Node.js, and is an organizer of NodeSchool SF.

Recent posts:

Implementing Infinite Scroll In Next Js With Server Actions

Implementing infinite scroll in Next.js with Server Actions

Infinite scrolling in Next.js no longer requires external libraries — Server Actions let us fetch initial data directly on the server.

Rahul Chhodde
Apr 19, 2024 ⋅ 10 min read
Integrating Django Templates With React For Dynamic Webpages

Integrating Django templates with React for dynamic webpages

Create a dynamic demo blog site using Django and React to demonstrate Django’s server-side functionalities and React’s interactive UI.

Kayode Adeniyi
Apr 18, 2024 ⋅ 7 min read
Using Aoi Js To Build A Bot For Discord

Using aoi.js to build a bot on Discord

Explore how the aoi.js library makes it easy to create Discord bots with useful functionalities for frontend applications.

Rahul Padalkar
Apr 17, 2024 ⋅ 9 min read
Web Components Adoption Guide: Overview, Examples, And Alternatives

Web Components adoption guide: Overview, examples, and alternatives

Evaluate Web Components, a set of standards that allow you to create custom HTML tags for more reusable, manageable code.

Elijah Asaolu
Apr 16, 2024 ⋅ 11 min read
View all posts

81 Replies to "Node.js ORMs: Why you shouldn’t use them"

  1. Really? Discussing the reasons why you should NOT use ORM? What about the reasons you SHOULD use ORM? The level of abstraction ORM can offer is elementary when dealing with large projects. And it can be beneficial in smaller projects as well. ORM has been proven in use for many years and has simplified the maintenance of many projects. And that you can use ORM incorrectly is a truism, as with every kind of framework. I think you’re just wrong when rejecting ORM as a solution.

  2. Not really convinced you should NOT use ORM either. I think what you advocating for in this blog post is more like an anti-pattern. We probably are in the era of microservices architectures and we want more simplicity of agility in software development but if you don’t at least structure your software with proven design patterns you’re just producing bad quality software difficult to maintain and to scale.

  3. I’m not sure what bug is under the skin of the other people commenting here, I think they hastily read the title and got frustrated, but I thought this was a well-written, succinct, and fair post. Maybe the title is baity, but the content was good and completely fair to ORMs. I think some of the comments got hasty and did not actually read the post. Thanks for succinctly pointing out some of the real dangers and common edges people brush up against when using ORMs.

  4. I was really curious when I landed on this page to understand why I should NOT use sequelize with NodeJS. But very disappointed with explanation.

    #1: This is not so true. You are NOT learning wrong. When you get some incorrect results, we always have to debug the sql log printed, so it is not correct.

    #2: Complex ORM calls can be difficult. Believe me, you are totally wrong here. See this following code I had to write to get the products, along with the child tables data:

    const sequelizeCondition = {
    where: {
    active: 1
    },
    attributes: [‘id’, ‘name’, ‘slug’, ‘description’, ‘ogDescription’, ‘metaTitle’, ‘metaDescription’, ‘ogTitle’, ‘order’, ‘type’, ‘aboutProduct’, ‘active’],

    include: [
    {
    model: db.productVariation,
    as: ‘productVariations’,
    where: {
    active: 1
    },
    attributes: [‘id’, ‘price’, ‘highPrice’, ‘qty’, ‘sku’, ‘size’, ‘color’],
    required: false,
    include: [{
    model: db.image,
    as: ‘images’,
    required: false,
    where: {
    active: 1
    },
    attributes: [‘id’, ‘src’, ‘alt’, ‘title’, ‘order’],
    }]
    },
    {
    model: db.review,
    as: ‘reviews’,
    where: {
    active: 1,
    },
    attributes: [‘id’, ‘review’, ‘rating’],
    required: false,
    include: [{
    model: db.user,
    attributes: [‘id’, ‘firstName’, ‘lastName’, ‘profilePic’],
    required: false,
    where: {
    active: 1
    }
    }]
    },
    {
    model: db.sizeChart,
    as: ‘sizeCharts’,
    where: {
    active: 1,
    },
    required: false,
    // include: [{
    // model: db.user,
    // attributes: [‘id’, ‘firstName’, ‘lastName’, ‘profilePic’],
    // required: true,
    // where: {
    // active: 1
    // }
    // }]
    },
    {
    model: db.productCategoryMapping,
    where: {
    active: 1,
    },
    required: false,
    include:[{
    model: db.category,
    where: {
    active: 1
    },
    required: true,
    attributes: [‘id’, ‘name’, ‘slug’, ‘order’],
    }]
    },
    ]
    };

    It is purely logical and as simple as any other SQL query can be.

    #3: Again, we can simply write a procedure for something we are unable to achieve in Sequelize.

    Thanks,
    V

  5. Being careful with ORM lead our projects using an intermediate SQL helper tool. It turned out to be very stable and low maintenance while ORM approaches are often a maintenance nightmare …

  6. The fact that vasty majority of people, including LogRocket and Martin Fowler using ORM the wrong way, doesn’t make all people use it the wrong way.

    Talk whatever you like. You got great SEO ranking right there, so I feel like writing some comment here.
    ORM has its merit and appropriate use case.
    Just don’t design your business logic around ORM.

    Read more details here:
    https://blog.cleancoder.com/uncle-bob/2013/10/01/Dance-You-Imps.html
    He publishes the article for quite some time, but I rediscover the same thing independently.

    Nope, I am not gonna avoid using ORM. I use it for mainly save, load, and some transaction capability to simplify things.

    Good luck with your “sweet spot” but bashing ORM under the wrong assumption is not cool.

  7. I think that some comments above are written without reading at all the post content.

    Besides this, i can’t understand IN ANY WAY how an ORM may prevent from understand any database query. It’s abstract i know, but whatever ORM you try you’ll smash your head again some “Where” or “Select”, and you’ll understand in broad terms what is a Join.

    I don’t agree neither with the fact that they are SO different. They have differents building,we can see it all. But in terms of abstraction ARE ALL THE SAME. So, you can’t understand a book if some periods are just shifted? Can’t follow a road if signals are in another language? Road is still a road, and book is still a book. The abstraction of ORMs looks so similar to me, i can’t really understand how someone can say that you may feel “disoriented” passing from one to another.

    Last but not least, we’re discussing of delays of seconds. An ORM have helped me save HOURS OF MY TIME for queries. More needs to be said?

  8. I have a hard time figuring out why I’m so resistant to even give ORM a try. It just “feels” wrong; but that’s probably because I’m a minimalist. I just don’t trust someone to generate and manage my SQL, having spent my share of adulthood looking at really complex Query Analyzer graphs to figure out what indexes to add, and how to order the fields so as to make it applicable to a specific query, but also to as many other queries as possible. Designing a truly robust enterprise-grade RDMBS is a momentous undertaking. And ORMs are a pathetic attempt at abstracting out its complexities.

  9. The irony is that Martin Fowler, in the article you link to, doesn’t come to the conclusion you do. To whit:

    > So ORMs help us deal with a very real problem for most enterprise applications. It’s true they are often misused, and sometimes the underlying problem can be avoided. They aren’t pretty tools, but then the problem they tackle isn’t exactly cuddly either. I think they deserve a little more respect and a lot more understanding.

    Ref: https://martinfowler.com/bliki/OrmHate.html

  10. As a developer with more than 30 years of application development experience using plan old SQL and many ORMs, I agree with your conclusion. Looks like we are still in the minority judging from the comments.

  11. you are right. I have seen in the industry how complicate a sql query can get over time. Maintaining such huge complicated queries can be nightmare in ORM over time as the creators will move on to other jobs. I have spent time to learn loop back and sequeluze, but were not happy when we find we need to write sql first then test it then export it to use it at orm. Truly hassle . For small task these orms seems blessings but when need grows it will become miserable

  12. Unfortunately this post is a coming short in why actually now a query builder is “the sweet spot”.
    I am not able to find good reasons why the second layer of abstraction is doing a good job?
    More concrete examples would be great. As with a query builder, you still have to build a lot of basic functions. Functions that a ORM performs at its basic layer. So you would be using your own functions on top of a query builder to create, read, update and delete items of a table. Boom, you created another ORM, just in your own style.

    I find as an analogy to this topic, I see the same with people using HTML forms to perform HTTP calls.
    You might be able to set up a HTML form and make it send some data to the server. It is a simple abstraction when you want to do one thing: submitting user data to a server with a page redirect/reload. But for anything else you need good knowledge about HTTP, once you turn to AJAX.

    I see it the same with ORMs, everyone is able to do a simple Item.find() query, but once you need more you need to dig deeper. It is the same with every abstraction. Specific tools are designed to do specific tasks. This is what makes them so powerful. You use ORMs not to abstract everything away, but most of the functions you need daily, and make that simple to use. If I’d have complex queries, I’d turn to GraphQL and use join-monster to do the hard work. You can’t have one solution to solve world hunger. There will always be solutions on top of solutions.

    Nowadays I’d turn to Strapi to do the bulk work of organizing my Rest or GraphQL API on top of an ORM that I can easily extend when needed.

  13. ORM’s absolutely can become a nightmare especially with more and more and more and more joins. THEY’RE performance nightmares. Just because you guys didn’t take the time to learn and implement what he is saying doesn’t mean he’s wrong. I guarantee you for any large scale db schema that your joins are sucking the life outta your application but hey what does it matter to you.. you don’t have to deal with it only the person retrieving your slow crawling data does.

    TLDR he’s right and you’re wrong deal with it.

  14. I personally can’t see any point in learning one new thing to avoid having to learn another new thing. I started to learn sequelize and really disliked it so just went back to writing SQL. Just couldn’t see the point in introducing an unnecessary and complicated layer of abstraction.

  15. Man… I been singing this song for about 10 years now, ever since I spent months undoing the N+1 nightmares created by ActiveRecord.

    People said I was crazy then and they say you’re crazy now.

    As I see it, I can either spend time mastering the ORM, or I can master SQL itself. I’ve discovered there are some stupendous features in postgresql for example, like CTEs, range types, fuzzy string matching, and array_agg that I would be horrified to give up at this point.

    Shine on you crazy diamond!

  16. Thanks for the article man.

    I totally agree and think that the negative comments are from people that didn’t read everything or didn’t get the point.

    I think that ORM is good for smaller projects but you should know how to use it in your architecture and how to use it with more complex situations.
    Almost every client project I work on have the problem that the developers are using the ORM mapped data structures as domain objects. Also using ORM can result in some crazy bugs when the ORM package makes a mistake and you end up debugging the raw queries to find the problem..

    I never use any ORM for my own projects anymore, for clients I adjust when the developers are ORM minded or the project itself already uses it.

  17. Seems like you completely missed the point of ORM:
    – the main purpose of ORM is decoupling persistence layer (database) from your application layer (not “easier use” or other non-sense)
    – with any ORM you can still write your own queries (as with any low lever “driver”)
    … there just these two points dismiss all “uneducated” arguments in this blog post.

  18. I agree with it.

    In a REST project to handle search API, we had about throughput of 18 per second, after removing ORM and optimizing the query, we managed to reach about 500.

    SQL Builders are sweet.

    But, ORMs are perfect for large projects, as it cause the project to fail and then I have a job to do, wiping away the ORM and optimizing the queries 😉

    But one good thing about ORM is database portability, which I do not care as I choose the database for each part of the project and changing it is out of the question.

    By the way give ‘sql-bricks’ a try it is a nice sql builder. It has also a special feature for PostgreSQL.

  19. You are correct for sure. Java projects of mine rely on ORMs and are a large nightmare without. JDBC requires so much extra work that just isn’t needed. Sure smaller projects don’t require it, but it is for sure useful. And this author person doesn’t know that SQL is still used a lot with ORMs. And also one of the most important things learned by programmers is that less code is less hassle. And every programmer needs to know that running everything in the database isn’t a “best-practice” tip taught in school.

  20. I Thing too much JavaScript, and smaller or medium size project has made this author think that orm is bad, try work with technology like .net, java, you will start having headache when your application starts to grow large, and many data manipulation is required. ORM is your friend and not your enemy.

  21. It seems you’ve made the crucial mistake of actually reading the article you’re referencing. 🙂

  22. ORMs are high level layers of indirection, modeling and replicating the DB model, due to just one main reason, developers don’t want to lear not just SQL, but DDL, DDM, DB normalizations, etc. I agree with the author, and would add another reason, most ORM frameworks, with the exception of Spring ORM, precludes the power of using DB stored procedures for example, what substracts a big deal of power to the developer toolbox. maintenance of the DB model, not just at DB model, but at the upper lever of the ORM, is … a bit more than a nightmare, and there is not a single mention to the fact that ROM frawks add tables, virews, etc… so, more processes running on the server, somtimes in a totally opaque way.

    Regarding the most used reason of the DB portability, In almost 50 years on the industry I have seen a complete DB migration from one RDBMS to another, one single time! Very low frequency to be a good reason !

    I agree with the Author, it is best learning SQL, stored procs, views, and learn to deal with the DB, first hand.

  23. As a beginner, I found this really interesting. Thanks. I agree with one commenter above that it would be helpful to see a more detailed explanation of how a query builder makes the choosing a color option problem easier to solve than it would be using just SQL. But that’s probably because I’m a beginner. 🙂

    Also, it is disappointing to see people react so negatively to a blog post. Oh well.

  24. Very nice Article, specially a lot of efforts done to take this research, Thank you very much for great efforts. I believe you have very good knowledge of topic. but I think ORM is best to use but in NodeJS we have to use something like Knex + Objection which is quit good combination. As in rails we use ActiveRecord and it is very helpful. As for performance in most of solution nobody care about. In raw queries people forget security most of time, so ORM bound them to all security.

  25. ORM’s change, they might be good for getting things out quickly, but 3 years later, they become the biggest pain. Everything works, but the ORM”s outdate so fast. In a proper design, the database tables get abstract away by the SQL and scripts/ stored procs. ORM’s do the opposite. Tight coupling to the tables. The only benefit I can see for ORM’s is that some of them allow one to change the database vendor/ database underneath quickly. Stored procs do the same – unfortunately not all database support stored procs and their language differs. If you stick to the main databases this should not be a problem.

  26. I don’t agree fully with the author. I see his point and understand his reasons to use the lower level adapters to speed up queries. Of course It can depend on a type of a project, but a large enough project that has to deal with 25+ models constantly changing will benefit most likely from using an ORM to avoid writing CRUD operations manually, plus managing schema changes separately from the code is an extra overhead (migrations are very important part of ORM). Talking about speed, there is a ceiling of what typical sql database can handle anyway and companies naturally progress to additional horizontally scalable tools to speed up things like distributed cache, data warehouse, sharding etc. Fast sql queries won’t be enough at certain level.

  27. ORMs are great for CRUD operations, _but in my personal experience_, then very soon become a burden and I find myself losing time looking on some heavily opinionated codebase to figure out how to generate a query I can easily write myself. Also — and specially for new programmers — hiding SQL leads to lack of understanding of relational databases and application suffer as soon as data grow a few hundred MB.

  28. It means you have the liability of ORM (setup, dependency management, learn dialect) for the easy CRUD operations and, then, rely on SQL for the more advanced features? It seems legit to me, but:
    – it’s not easy to play with SQL queries together with ORM models, so you end up with two mappings, one using ORM models and another different using POJO or arrays, with completely different interfaces;
    – if the contributors base is not used to write SQL how you think the quality of the SQL written for the non-trivial cases will be?

  29. I started out using ORMs and I can tell you for a fact that I did not need to learn proper SQL to use them. That was limiting (I was also a noob developer, so there was that)

    Later on I learned SQL and started writing raw SQL queries. You know what? I liked it a lot more because I could just take queries right out of a tool like PG Admin, paste it into my code, and I knew it would work. I still do that for complex queries.

    Knex hits a sweet spot for me, too. It’s so sql-like that I can see what is going on without having to burn any brain cells translating it. It returns a promise, which is convenient, and it has a very concise syntax. I tried using it with Bookshelf for awhile but down the road I just went back to Knex by itself.

  30. No. The author is quite correct. He’s simply warning you about the consequences of boiling the ocean when you just need a cup of tea. These days, people try to abstract everything away to build any size project, I say no if you are doing it in software, but yes if you are creating hardware. I have been writing this stuff for 20 years, (Every day). ORM’s are only good for learning how to build code generators that create that cup of tea that you need. Use or create your own code generators that creates just what you need, when you need it.]

    So Really! Not using ORM is a very smart thing not to do.
    Really!

  31. I think the only time to use ORM is when your software must support a variety of databases (e.g. distributed open source software). When you are in control of the execution environment, you will be more likely to have to change the ORM than the database.

  32. I still don’t get this post. When dealing with complex queries you can make an ORM execute a raw query string but when dealing with simple queries the ORM works really well. Most of the time an application uses simple queries but if you’ve created an application which is using a complex query all the time then I must say that instead of learning SQL you must first learn database design because most likely your entire schema sucks.

  33. thanks for warnings.. i was confused about it.. by your article with answers i reach to solution for my learning path.. thanks a lot..

  34. I think subqueries are super useful, common, and often used … yet the ORM requires you to write “raw” SQL to achieve it. Are you saying anyone who uses a subquery in their design has a schema that “sucks”? I’m gonna have to strongly disagree.

  35. Well, having done this for like 32 years, including a bunch of years as a RDBMS administrator and query optimizer on staff, eeeehhhhhhhhhh…. ORMs are great for getting stuff done quickly and more simply, and with actual objects with predictable shapes and functions.

    Should every developer fully understand all the SQL goodness underneath? Probably, yeah. But ORMs let you (most of the time) not really care what the data layer is and lets you prototype on one layer locally and deploy to another, a clustered setup, a DOCKER’d setup, a REST setup, or a host of other things, without really a lot of changes or too-configurable-for-stability code building.

    On balance, ORMs are good.

  36. Yeah this is old and I came here because it appeared on a google search so I was curious.

    On in your simple example, you say you don’t want data from the table dish, so why did you ask for it. Just because you have an association defined in the model does not mean you have to ask for it every time. You never show us your call to retrieve the data. In Sequelize you are obviously calling the dish model to get your results, why not call from the ingredients model and if there is an association with dish just don’t include it.

    Simplified foo example

    const ingredients = await Ingredients.findAll({ where: { itemid: itemid, include: item });

    Your dissing an ORM when it is obviously a developer mistake you made.

    Also if you don’t want a Left Outer Join then just include the required: true parameter and you won’t get it.

  37. Yeah, this post illustrates a few things:

    1. You hadn’t used a great ORM when you wrote this. The Django ORM, for example, is a great ORM and much better than the shitty javascript/typescript ones. Docs are fantastic, too.
    2. You didn’t realize the power in hooking up a great ORM to other integration points (Django and Rails can spit out authenticated CRUD endpoints in REST from a single table definition with about 5 additional lines of code, for instance.)
    3. You discount the day-to-day drudgery involved in quickly prototyping or bootstrapping a project which may involve cranking out a lot of code where writing out a bunch of simple operations in SQL is unproductive at best. Most people, at the end of the day, are writing web apps, and so, on balance, most projects would do well to have a good ORM.
    4. You believe that learning an ORM is such a big investment that it inhibits you from actually learning SQL. Personally, I find this pretty laughable as neither SQL or ORMs are rocket science or even particularly hard, but I suppose it’s all relative to the time invested.
    5. You apparently think that you might switch ORMs a lot? Who cares how many syntaxes there are for various (crappy) JavaScript ORMS – you’re not gonna use more than 1 or 2, most likely. If you switch jobs to a new place where they use the same language with a new ORM let’s face it: learning some new ORM syntax with plenty of examples in the code will be the least of your problems while you’re figuring out a new code base.

    Also, the people saying ORMS are ruining your performance: you’re focusing on an almost irrelevant problem, practically speaking.

    I’m old enough to have read “SQL for Smarties” in paperback at the turn of the century but 99% of the time I’ve never needed that kind of knowledge (though it’s super fun to bust it out when called for!)

    Yes, there’s going to be a few hot spots in your code where you can mess up the joins in ORMS, but they’re probably between 1% to 5% of the SQL you’ll actually create in an ORM. Simple profiling (or even just minding the slow query log in your database) is the bare minimum for being a competent developer. Also, if you know even a TINY bit about SQL you’ll have a hunch when the ORM might generate a bad query plan.

    Either way any decent ORM allows you to print the SQL plan, then tweak things or even drop down to raw SQL if you need to. Focusing on the low percentage of optimization problems you could temporarily run into while disregarding the vast majority of cases where it stops you writing tons of boilerplate code is silly.

  38. I don’t agree with the author.

    I haven’t tried Node.js ORMs, I actually got here trying to figure out why Node.js ORMs weren’t as popular as I thought.

    Please, If you haven’t tried, check out the Django ORM or how FastAPI integrates with SQLAlchemy.

    Honestly, don’t you get tired of writing the same database schema that supports the same CRUD operations over and over?
    Or tired of updating the SQL schema and migration scripts with the updated table schema, plus the SQL query in your code, plus the serializer / de-serializer… every time the schema changes?

    Those are manual tasks that are prone to error that could end in production.

    I advocate for automating everything, and ORMs are part of that automation.

  39. You do not use an ORM for its querying capabilities, but rather for its capability to abstract from storage considerations.
    Benchmarking an ORM with queries is like testing a cruise ship for its speed.

    – Focus on your business logic, implement it within your domain models,
    – Implement a service layer, where each controller provides a business use case, by :
    1. fetching domain models from your ORM
    2. orchestrating invocation of BL methods/operations on your domain models
    3. persisting your updated/created domain models

    – Yes, it’s “slow”. But it’s clean, production-ready and works damn fine !

  40. One of the most important reasons to use ORM is preventing SQL injections. Personally I don’t like adding an abstraction layer to my codes until I have a good reason for that, but I can not ignore the treats of SQL injection and I don’t like to manually validate all inputs from users to see if there is a treat in it!

  41. Well, I think it depends, … if you need to support multiple DBMS, perform dynamic query building and performing CRUD queries then using an ORM is fine, when you need to deal with low level SQL optimization, complex query building, dynamic structure at runtime etc … then sometimes you’ll have hard times.

    You can always opt for a mix of ORM and not-ORM, … but as for all the ther things this is something that should be done balancing pros and cons.

Leave a Reply