diff --git a/src/indexes/decorators.ts b/src/indexes/decorators.ts index dbe37e6f..bf0c75cd 100644 --- a/src/indexes/decorators.ts +++ b/src/indexes/decorators.ts @@ -3,10 +3,11 @@ import { IndexSpecification } from 'mongodb'; import { setIndexMetadata } from './metadata'; export function Index(metadata?: Partial) { - return (target: any, property: string) => + return function (target: any, property: string) { setIndexMetadata( target, property, metadata === undefined ? {} : metadata ); + }; } diff --git a/src/indexes/metadata.ts b/src/indexes/metadata.ts index 3704b6ac..3e72e750 100644 --- a/src/indexes/metadata.ts +++ b/src/indexes/metadata.ts @@ -19,12 +19,11 @@ export function setIndexMetadata( ) { let targetMetadata: IndexMetadata[] | undefined = Reflect.getMetadata( INDEX_METADATA_NAME, - target + target.constructor ); if (targetMetadata === undefined) { targetMetadata = []; } - targetMetadata.push({ property, metadata }); Reflect.defineMetadata( INDEX_METADATA_NAME, @@ -53,7 +52,8 @@ export async function createIndexes( // declared indexes const indexesMetadata = getIndexMetadatas(ModelClass); - const collection = await manager.getCollection(ModelClass); + const collection = manager.getCollection(ModelClass); + if (indexesMetadata !== undefined) { for (const index of indexesMetadata) { const mongoIndex = { @@ -90,6 +90,14 @@ export async function createIndexes( } } if (indexes.length > 0) { - await collection.createIndexes(indexes); + try { + await collection.createIndexes(indexes); + } catch (e) { + throw new Error( + `Unable to create index on collection ${ + collection.namespace + }: ${JSON.stringify(indexes)} ${e.message as string}` + ); + } } }