Skip to content

EventSubscriber not getting updated values for update using queryBuilder and manager.update methods. #2246

Closed as not planned

Description

@PavanBahuguni

Issue type:

[x] question
[ ] bug report
[ ] feature request
[ ] documentation issue

Database system/driver:

[ ] cordova
[ ] mongodb
[ ] mssql
[ ] mysql / mariadb
[ ] oracle
[x] postgres
[ ] sqlite
[ ] sqljs
[ ] react-native

TypeORM version:

[ ] latest
[ ] @next
[ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:
Whenever entity is update using queryBuilder update method or entity update method, the EventSubscriber's afterUpdate method gets triggered, but the UpdateEvents entity, databaseEntity, updatedColumns, updateRelations are always empty. These fields are populated only when the updates are done using save methods. Is this intended behaviour.

Activity

  1. pleerock commented on Jun 1, 2018

    @pleerock
    Member

    any code example?

  2. CanKattwinkel commented on Jun 3, 2018

    @CanKattwinkel

    @pleerock i think I runned into the same issue. I have a beforeUpdate method in an EntitySubscriber. The method is called correctly but in side the event the .entity property is undefined.

    import {EntitySubscriberInterface, EventSubscriber, InsertEvent} from 'typeorm';
    import {ParkingSpotEntity} from '../modules/parkingspot/parkingspot.entity';
    import {UpdateEvent} from 'typeorm/subscriber/event/UpdateEvent';
    
    
    @EventSubscriber()
    export class SomeListener implements EntitySubscriberInterface<ParkingSpotEntity> {
    
      listenTo () {
        return ParkingSpotEntity
      }
      afterLoad?(entity: ParkingSpotEntity): Promise<any> | void {
        console.log("afterLoad", entity)
      };
      
      beforeUpdate?(event: UpdateEvent<ParkingSpotEntity>): Promise<any> | void {
        console.log("beforeUpdate", event.entity)
      };
    }
    
    

    I think this applies for beforeInsert, afterInsert, beforeUpdate, afterUpdate, beforeRemove, afterRemove too. Only afterLoad has the entity (maybe because the signature is different).

    console.logs after update, then load the entity:

    beforeUpdate undefined
    afterLoad ParkingSpotEntity {
      id: 5,
      lat: '48.768496',
      lng: '9.180188',
      available: true,
     ....}
    

    E: "version": "0.2.6",

  3. added a commit that references this issue on Jun 3, 2018
  4. CanKattwinkel commented on Jun 3, 2018

    @CanKattwinkel

    I tried to provide a test case covering the issue in a fork:

    https://github.com/CanKattwinkel/typeorm/blob/master/test/github-issues/2246/issue-2246.ts

    I'm not too familiar with chai, so I didn't know how to provide a spy for the ParkingSpotEntitySubscriber. And having expect statements in the actual implementation (ParkingSpotEntitySubscriber.ts) felt too fragile too. So i created global vars for testing.. Anyway, it proves the case: event.entity is undefined in ParkingSpotEntitySubscriber#beforeUpdate

  5. pleerock commented on Jun 4, 2018

    @pleerock
    Member

    what if you use save instead of update?

  6. CanKattwinkel commented on Jun 4, 2018

    @CanKattwinkel

    @pleerock then it works - is this the desired behavior? Because this feels confusing.

  7. pleerock commented on Jun 4, 2018

    @pleerock
    Member

    Listeners are confusing but because of flexibility and functionality orm provides. With save you can always have an entity or partial entity which you insert/update. With update and update query builder you have more like a set of values to be used in UPDATE query. For example:

    update({
         id: 1,
         counter: () => "counter + 1"
    });

    counter in entity is actually a number, but this is a valid syntax for update, and if we pass this update set to listener we can't call it entity anymore.

  8. CanKattwinkel commented on Jun 4, 2018

    @CanKattwinkel

    Thanks for your patience, I get it now.

    Since this is not quite obvious, should it be mentioned in the docs?

    https://github.com/typeorm/typeorm/blob/master/docs/listeners-and-subscribers.md#beforeupdate

  9. pleerock commented on Jun 4, 2018

    @pleerock
    Member

    TypeORM is huge and has lot of small functionality and lot of quirks. There are hundred such small details all of them simply can't be documented not only because its impossible to keep in mind all small facts like this, but also because it will complicate documentation. Maybe I'll add this to documentation in the future.

  10. pleerock commented on Feb 25, 2019

    @pleerock
    Member

    wow, wow so many dislikes on my above post ^ Okay, okay, now I definitely know we need to add this to the docs.

  11. jalooc commented on Nov 15, 2019

    @jalooc

    But then, what's the preferred approach to reliably act upon update of an entity, with data about the entity itself available? By reliably, I mean no matter of the way the data is updated, whether is .save() or .update(), or query builder or whatever.

    I don't want to be forced to remember to use certain way of updating just because somewhere on the other end of the repository there's a subscriber that reacts differently to different methods.

  12. vinimdocarmo commented on Dec 10, 2019

    @vinimdocarmo

    I don't want to be forced to remember to use certain way of updating just because somewhere on the other end of the repository there's a subscriber that reacts differently to different methods.

    I second this!

    Is there any other safer method to get the old values of my entity in my subscriber? I tried to use event.manager to fetch the old values from database, but it seems to be using the same transaction the update is using.

  13. or2008 commented on Dec 20, 2019

    @or2008

    I don't want to be forced to remember to use certain way of updating just because somewhere on the other end of the repository there's a subscriber that reacts differently to different methods.

    I second this!

    Is there any other safer method to get the old values of my entity in my subscriber? I tried to use event.manager to fetch the old values from database, but it seems to be using the same transaction the update is using.

    +1

  14. HunterJS-bit commented on Dec 26, 2019

    @HunterJS-bit

    @pleerock
    But how can I then get updated value, or proprties that are updated ?

  15. muyoucun557 commented on Mar 20, 2020

    @muyoucun557

    Listeners are confusing but because of flexibility and functionality orm provides. With save you can always have an entity or partial entity which you insert/update. With update and update query builder you have more like a set of values to be used in UPDATE query. For example:

    update({
         id: 1,
         counter: () => "counter + 1"
    });

    counter in entity is actually a number, but this is a valid syntax for update, and if we pass this update set to listener we can't call it entity anymore.

    if I set valid value of column, when call update , subscriber get entity is undefined, this is unfriendly.

  16. muyoucun557 commented on Mar 20, 2020

    @muyoucun557

    @pleerock
    But how can I then get updated value, or proprties that are updated ?

    call save

  17. zeele commented on Jul 26, 2020

    @zeele

    I don't want to be forced to remember to use certain way of updating just because somewhere on the other end of the repository there's a subscriber that reacts differently to different methods.

    I second this!
    Is there any other safer method to get the old values of my entity in my subscriber? I tried to use event.manager to fetch the old values from database, but it seems to be using the same transaction the update is using.

    +1

    +1

  18. tafelito commented on Aug 2, 2020

    @tafelito

    @pleerock have you had the time to documented this? I didn't find anything on the documentation and I still struggle to understand when the subscriber is actually called. If I use a QueryBuilder, then the afterUpdate is called without data. Same as using Entity.update. Then If I use Entity.save it does get called, but only with the values I set in the entity instance

    In my case, I need to use the QueryBuilder or the update since I need to return the completed entity values after the update. What would be the best to do this today?

  19. sandeshgb commented on Aug 12, 2020

    @sandeshgb

    @tafelito @pleerock as mentioned above I'm struggling on same thing. We can't use save() all the time, at times based on certain scenarios we have to use update().
    How to tackle this?

  20. vemundeldegard commented on Aug 25, 2020

    @vemundeldegard

    I am getting empty arrays for the following event.updatedColumns: [] , event.updatedRelations: [] . I have tried using both.update(), connection.query() with manual SQL and repositoryManager to update. All resulted in no metadata to use.

    What worked for me is using .save() to trigger afterUpdate subscription. From the docs: "If you run save without modifying anything from the model, @BeforeUpdate and @AfterUpdate will not run."

    const order = await Order.findOne(id);
    if (!order) throw new ApolloError("No order found", "NOT_FOUND");
    order.baseCurrency = "SEK";
    order?.save();
    
  21. NickKelly1 commented on Aug 28, 2020

    @NickKelly1

    TypeORM gives you lots of control over your database interactions. You can use high-level, fully-featured but less efficient operations, or low-level and fast operations.

    • When executing high-level operations (EntityManager.save), TypeORM has full access to the entity and can do additional queries to determine whether inserting or updating. Therefore TypeORM can call subscribers with entities.
    • When executing primitive operations ( EntityManager.insert, EntityManager.update, EntityManager.delete), TypeORM does not always have access to entities, but does know the operation. Therefore TypeORM can call subscribers, but cannot always provide the entities.
    • When executing raw SQL queries (QueryRunner.query), TypeORM does not know what you're doing and doesn't have access to entities or subscribers.

    Each method has tradeoffs. You have to decide the best fit for your use case.

    If you want to see exactly what the orm is doing, turn on logging and check out the SQL being executed for your operations

  22. driescroons commented on Sep 10, 2020

    @driescroons

    @NickKelly1 you can call the save method instead of the update method
    carbon (1)

  23. karladler commented on Dec 10, 2020

    @karladler

    maybe the listenerMethod should just be renamed (+ aliased for backwards compatibility) to afterSaveto avoid this confusion.

  24. shaqqan commented on Jul 23, 2024

    @shaqqan
        public async deleteNotificationByGiveUp(gameId: number) {
        // Load the notifications to be deleted with all fields
        const notifications = await this.notificationRepository.find({
            where: { gameId: gameId },
        });
    
        // Remove the notifications
        await this.notificationRepository.remove(notifications);
    }
    
    async afterRemove(event: RemoveEvent<Notification>) {
        console.log(`AFTER ENTITY REMOVED: `, event.entityId);
        console.log(`AFTER ENTITY REMOVED: `, event.entity);
        // await this.clearNotificationCache(event);
    }
    
    I'm doing remove but the event value is undefined
    
  25. github-actions commented on Sep 18, 2025

    @github-actions

    TypeORM has returned to active development after recently transitioning to new leadership (see related announcement).

    As part of the new team's efforts to prioritise work on the project moving forward, it is necessary to clean up the backlog of stale issues.

    🧹 This issue is being automatically closed because it has had no activity in the last 6 months.
    If you believe this issue is still relevant, feel free to comment below and the maintainers may reopen it. Thank you for your contribution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions