Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MongoDB update make changes only to first matched document #7788

Closed
2 of 21 tasks
SnapeEye opened this issue Jun 23, 2021 · 5 comments · Fixed by #7803
Closed
2 of 21 tasks

MongoDB update make changes only to first matched document #7788

SnapeEye opened this issue Jun 23, 2021 · 5 comments · Fixed by #7803

Comments

@SnapeEye
Copy link
Contributor

SnapeEye commented Jun 23, 2021

Issue Description

Hello!
Got some problems when I need to update data in MongoDB (working in NestJS). I have my Repository class, there I call update method, pass all necessary params. But when operation is done, only one entity is updated.

Expected Behavior

It is expected all entities, which were matched to my search params, to be updated

Actual Behavior

For now, only the first entity, matching the search params, is updated.

Steps to Reproduce

  1. Create 1-2 entity with name 'Test'
  2. Create 1 entity with name 'Original'
  3. Update all entities with name 'Test', changing it to name 'Updated'
@Entity('test')
export class TestEntity {
  @ObjectIdColumn()
  _id: string;

  @PrimaryColumn()
  id: string;

  @Column()
  name: string;
}

@EntityRepository(TestEntity)
export class TestRepository extends Repository<TestEntity> {
  async reproduce(): Promise<void> {
    await this.save({
      id: '1',
      name: 'Test',
    });
    await this.save({
      id: '2',
      name: 'Test',
    });
    await this.save({
      id: '3',
      name: 'Original',
    });
    await this.save({
      id: '4',
      name: 'Test',
    });
    console.log('Before update:');
    console.log(await this.find());
    await this.update({ name: 'Test' }, { name: 'Updated' });
    console.log('After update:');
    console.log(await this.find());
  }
}

Logs:

Before update:
[
  TestEntity { _id: 60d2ff281069ed4ed8db03fd, id: '1', name: 'Test' },
  TestEntity { _id: 60d2ff281069ed4ed8db03fe, id: '2', name: 'Test' },
  TestEntity {
    _id: 60d2ff281069ed4ed8db03ff,
    id: '3',
    name: 'Original'
  },
  TestEntity { _id: 60d2ff281069ed4ed8db0400, id: '4', name: 'Test' }
]
After update:
[
  TestEntity {
    _id: 60d2ff281069ed4ed8db03fd,
    id: '1',
    name: 'Updated'
  },
  TestEntity { _id: 60d2ff281069ed4ed8db03fe, id: '2', name: 'Test' },
  TestEntity {
    _id: 60d2ff281069ed4ed8db03ff,
    id: '3',
    name: 'Original'
  },
  TestEntity { _id: 60d2ff281069ed4ed8db0400, id: '4', name: 'Test' }
]

My Environment

Dependency Version
Operating System Windows 10 Enterprise
Node.js version v14.17.0
Typescript version v4.3.2
TypeORM version v0.2.34

Relevant Database Driver(s)

  • aurora-data-api
  • aurora-data-api-pg
  • better-sqlite3
  • cockroachdb
  • cordova
  • expo
  • mongodb
  • mysql
  • nativescript
  • oracle
  • postgres
  • react-native
  • sap
  • sqlite
  • sqlite-abstract
  • sqljs
  • sqlserver

Are you willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time, and I know how to start.
  • Yes, I have the time, but I don't know how to start. I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.
@SnapeEye
Copy link
Contributor Author

I've spent some time and found potential solution to the issue:

find override function in MongoEntityManager calls updateOne function to perform the update operation.
I changed this call to updateMany and the update worked as was expected.

image

@SnapeEye
Copy link
Contributor Author

Got the fix solution, but unable to push branch with changes...
Maybe someone is able to make changes himself?
Not quite good issue...

@imnotjames
Copy link
Contributor

Please feel free to try to get the changes up in a PR or post the diff here.

@SnapeEye
Copy link
Contributor Author

SnapeEye commented Jun 25, 2021

Please feel free to try to get the changes up in a PR or post the diff here.

I've read all the roadmap of contribution, made changes and tests but was unable to push branch with changes. Got 2 different commands to try:

$ git push -f
fatal: The current branch mongo-all-documents-update has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin mongo-all-documents-update
$  git push --set-upstream origin mongo-all-documents-update
info: please complete authentication in your browser...
remote: Permission to typeorm/typeorm.git denied to SnapeEye.
fatal: unable to access 'https://github.com/typeorm/typeorm/': The requested URL returned error: 403

But, anyway, here is the diff (MongoEntityManager.ts). Maybe you can help with adding it.

    async update<Entity>(target: EntityTarget<Entity>, criteria: string | string[] | number | number[] | Date | Date[] | ObjectID | ObjectID[] | FindConditions<Entity>, partialEntity: QueryDeepPartialEntity<Entity>): Promise<UpdateResult> {
        if (Array.isArray(criteria)) {
            await Promise.all((criteria as any[]).map(criteriaItem => {
                return this.update(target, criteriaItem, partialEntity);
            }));

        } else {
            const metadata = this.connection.getMetadata(target);
-            await this.updateOne(target, this.convertMixedCriteria(metadata, criteria), { $set: partialEntity });
+            await this.updateMany(target, this.convertMixedCriteria(metadata, criteria), { $set: partialEntity });
        }

        return new UpdateResult();
    }

@imnotjames
Copy link
Contributor

Looks like you need to fork the repo - you're trying to push directly to typeorm/typeorm. You should fork the repo & push to that instead.

https://guides.github.com/activities/forking/

SnapeEye added a commit to SnapeEye/typeorm that referenced this issue Jun 25, 2021
Update operation should update all matched documents, but now it updates the first found document

Closes: typeorm#7788
imnotjames pushed a commit that referenced this issue Jun 26, 2021
mongo update operation should update all matched documents, but now it updates the first found document

fixes #7788
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants