question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

MongoDB update make changes only to first matched document

See original GitHub issue

Issue Description

Hello! Got some problems when I need to update data in MongoDB (working in NestJS). I have my Repository<Entity> 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.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
imnotjamescommented, Jun 25, 2021

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/

0reactions
SnapeEyecommented, 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();
    }
Read more comments on GitHub >

github_iconTop Results From Across the Web

Why mongodb only updates the first matching document in the ...
I want to update all the documents whose name is “Nithin” as age=60. If we execute the following query it will only update...
Read more >
db.collection.update() — MongoDB Manual
By default, the db.collection.update() method updates a single document. Include the option multi: true to update all documents that match the query criteria....
Read more >
Querying and updating documents Using MongoDB Compass
So, documents on a database can be changed using: updateOne, updateMany and replaceOne. For Update methods each take a filter document as their...
Read more >
MongoDB Animated : Updating elements in arrays
By combining the $ positional operator with $set , we can update properties from the first array element that matches our query document...
Read more >
MongoDB - Update Single Document Using MongoShell
updateOne() method only accepts a document that contains update operator expressions. · This method can be used in the multi-document ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found