Skip to content

Commit

Permalink
fix(typegoose): allow undefined id field when updating or creating
Browse files Browse the repository at this point in the history
  • Loading branch information
doug-martin committed Jul 27, 2021
1 parent db5bf44 commit c2031aa
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,20 @@ describe('TypegooseQueryService', () => {
'Id cannot be specified when updating or creating',
);
});

it('should not reject if the entity contains an undefined id', async () => {
const entity = testEntityToCreate(TEST_ENTITIES[0]);
const queryService = moduleRef.get(TestEntityService);
const created = await queryService.createOne({ ...entity, id: undefined });
expect(convertDocument(created)).toEqual(expect.objectContaining(entity));
});

it('should not reject if the entity contains an undefined _id', async () => {
const entity = testEntityToCreate(TEST_ENTITIES[0]);
const queryService = moduleRef.get(TestEntityService);
const created = await queryService.createOne({ ...entity, _id: undefined });
expect(convertDocument(created)).toEqual(expect.objectContaining(entity));
});
});

describe('#deleteMany', () => {
Expand Down Expand Up @@ -521,6 +535,18 @@ describe('TypegooseQueryService', () => {
'Id cannot be specified when updating',
);
});

it('should not reject if the update contains an undefined id', async () => {
const queryService = moduleRef.get(TestEntityService);
const entitiesToUpdate = TEST_ENTITIES.slice(0, 5);
const filter = {
stringType: { in: entitiesToUpdate.map((e) => e.stringType) },
};
await queryService.updateMany({ stringType: 'updated', id: undefined }, filter);
const entities = await queryService.query({ filter: { stringType: { eq: 'updated' } } });
expect(entities).toHaveLength(entitiesToUpdate.length);
expect(new Set(entities.map((e) => e.id))).toEqual(new Set(entitiesToUpdate.map((e) => e.id)));
});
});

describe('#updateOne', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,9 +238,9 @@ export class TypegooseQueryService<Entity extends Base>

private ensureIdIsNotPresent(e: DeepPartial<Entity>): void {
if (
Object.keys(e)
.filter((v) => typeof e[v] !== `undefined`)
.find((f) => f === 'id' || f === '_id')
Object.entries(e)
.filter(([k, v]) => typeof v !== `undefined`)
.find(([k]) => k === 'id' || k === '_id')
) {
throw new Error('Id cannot be specified when updating or creating');
}
Expand Down

0 comments on commit c2031aa

Please sign in to comment.