Search code examples
mongodbmongoosetypegoose

Change Typegoose collection name after initialize


I am using typegoose to create models. During creation of model, I found that it is possible to provide collection name. But once it is assigned, I am not able to find way to modify it.

export const MyModel: ModelType<MyModel> = new MyModel().setModelForClass(MyModel, {
    existingMongoose: mongoose,
    schemaOptions: {collection: 'my_collection_name'}
});

So in above MyModel, I want to change collection name where I am importing.

How can I change a collection name in model? Or am I only left with the option of creating this model where I want to use it?


Solution

  • Never mind. I just had to make function of exported object. So I changed it to below, so that I can pass collectionName where I am consuming this model.

    const DocumentFieldBooleanValueModel = (collectionName: string) : ReturnModelType<typeof DocumentFieldBooleanValue, BeAnObject> => {
      return getModelForClass(DocumentFieldBooleanValue, {
        schemaOptions: { collection: collectionName },
      });
    };
    
    export { DocumentFieldBooleanValueModel };
    

    So now above exported model function I can use as below.

    DocumentFieldBooleanValueModel('MyCustomCollectionName')
    

    And it will give same typegoose model.