Skip to content

Commit

Permalink
fix(mongo): ensure assign on object properties won't ignore changes
Browse files Browse the repository at this point in the history
Closes #5158
  • Loading branch information
B4nan committed Feb 1, 2024
1 parent 0e646a9 commit bd22d7c
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 2 deletions.
3 changes: 1 addition & 2 deletions packages/core/src/entity/EntityAssigner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,7 @@ export class EntityAssigner {
}

if (options.mergeObjects && Utils.isPlainObject(entity[propName]) && Utils.isPlainObject(value)) {
entity[propName] ??= {};
Utils.merge(entity[propName], value);
entity[propName] = Utils.merge({}, entity[propName], value);
} else if (!prop || prop.setter || !prop.getter) {
entity[propName] = value;
}
Expand Down
66 changes: 66 additions & 0 deletions tests/features/entity-assigner/GH5158.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import {
Entity,
JsonType,
PrimaryKey,
Property,
} from '@mikro-orm/core';
import { MikroORM, ObjectId } from '@mikro-orm/mongodb';

@Entity()
class User {

@PrimaryKey()
_id!: ObjectId;

@Property({ type: JsonType })
methods: { method1?: string; method2?: string } = {};

}

let orm: MikroORM;

beforeAll(async () => {
orm = await MikroORM.init({
dbName: '5158',
entities: [User],
});
});

afterAll(async () => {
await orm.close();
});

test('should update json properties with assign()', async () => {
// initialize user
const user1 = new User();
user1.methods = { method1: '1', method2: '1' };
const em1 = orm.em.fork();
await em1.persistAndFlush(user1);

// verify that it was persisted properly
const emRead1 = orm.em.fork();
const result1 = await emRead1.findOneOrFail(User, user1._id);
expect(result1.methods).toEqual({ method1: '1', method2: '1' });

// updating JSON property without assign() should work
const em2 = orm.em.fork();
const user2 = await em2.findOneOrFail(User, user1._id);
user2.methods = { method1: '1', method2: '2' };
await em2.persistAndFlush(user2);

// verify that it was persisted properly
const emRead2 = orm.em.fork();
const result2 = await emRead2.findOneOrFail(User, user1._id);
expect(result2.methods).toEqual({ method1: '1', method2: '2' });

// updating JSON property with assign() should work
const em3 = orm.em.fork();
const user3 = await em3.findOneOrFail(User, user1._id);
em3.assign(user3, { methods: { method2: '3' } });
await em3.persistAndFlush(user3);

// verify that it was persisted properly
const emRead3 = orm.em.fork();
const result3 = await emRead3.findOneOrFail(User, user1._id);
expect(result3.methods).toEqual({ method1: '1', method2: '3' });
});

0 comments on commit bd22d7c

Please sign in to comment.