From 036baaa443c5c50681d9f4f991c3d350cad223fe Mon Sep 17 00:00:00 2001 From: ChengLei Shao Date: Sun, 3 Apr 2022 19:45:59 +0800 Subject: [PATCH] fix: toJSON with null association (#260) --- .../src/__tests__/repository/update.test.ts | 60 +++++++++++++++++++ packages/database/src/model.ts | 2 +- 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 packages/database/src/__tests__/repository/update.test.ts diff --git a/packages/database/src/__tests__/repository/update.test.ts b/packages/database/src/__tests__/repository/update.test.ts new file mode 100644 index 000000000..d017f553e --- /dev/null +++ b/packages/database/src/__tests__/repository/update.test.ts @@ -0,0 +1,60 @@ +import { Collection, Database, mockDatabase } from '@nocobase/database'; + +describe('update', () => { + let db: Database; + let User: Collection; + let Tag: Collection; + afterEach(async () => { + await db.close(); + }); + + beforeEach(async () => { + db = mockDatabase(); + User = db.collection({ + name: 'posts', + fields: [ + { type: 'string', name: 'title' }, + { + type: 'belongsToMany', + name: 'tags', + }, + ], + }); + + Tag = db.collection({ + name: 'tags', + fields: [ + { + type: 'string', + name: 'name', + }, + { + type: 'belongsToMany', + name: 'posts', + }, + ], + }); + + await db.sync(); + }); + + it('should update tags to null', async () => { + await db.getRepository('posts').create({ + values: { + title: 'p1', + tags: [{ name: 't1' }], + }, + }); + + const [p1] = await db.getRepository('posts').update({ + values: { + tags: null, + }, + filter: { + title: 'p1', + }, + }); + + expect(p1.toJSON()['tags']).toEqual([]); + }); +}); diff --git a/packages/database/src/model.ts b/packages/database/src/model.ts index 30c7642db..0f31fa7e8 100644 --- a/packages/database/src/model.ts +++ b/packages/database/src/model.ts @@ -40,7 +40,7 @@ export class Model { const handles = [this.sortAssociations]; - return handles.reduce((carry, fn) => fn.apply(this, [carry, options]), arrayOfObj); + return handles.reduce((carry, fn) => fn.apply(this, [carry, options]), arrayOfObj || []); }; const opts = {