TypeORM Dynamic Collection (Table) name when using MongoDB

Ashok Vishwakarma
2 min readFeb 17, 2021

TypeORM is one of the most popular Database ORMs available for NodeJS which supports #TypeScript out of the box. It also can be used on Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms. It supports both Active Record and Data Mapper patterns, unlike all other JavaScript ORMs currently in existence, which means you can write high quality, loosely coupled, scalable, maintainable applications in the most productive way.

No doubt its a great tool but have you ever face a situation where the collection name is dynamic and you want to do database operations on that? Yeah, searching google tells you that there is no way you can do that as it contradicts the basic fundamentals of having an ORM in the first place.

But sometimes we have to do it anyway, so here is the way you can achieve it if you are using TypeORM with MongoDB

Define a Dummy Entity (Model) with a similar schema as your dynamic collection (table) would be.

@Entity()
export class Dummy{
@Column()
firstName: string;
@Column()
lastName: string;
@Column()
email: string;
}

Create a TyoeORM Repository using this Dummy entity

const repository = getRepository(Dummy);

Change the repository table name in its metadata

repository.metadata.tableName = "dynamic";

Continue using the repository

// data comes from dynamic collection 
// instead of dummy collection
const data = await repository.find();// saved in dynamic collecitonconst saved = await repository.save(repository.create({...}))

Conclusion

I had a very minimum use case to insert and fetch data from the dynamic collection which work perfectly fine and I have not tested the same for more complex requirements such as having relations mapping and etc. Let me know if it works for all other cases.

That’s all for this, please do share your thoughts and how you have solved such issues in your project.

--

--

Ashok Vishwakarma

@GoogleDevExpert — #WebTechnologies & @angular | #Principal #Architect at @Naukri | #Entrepreneur | #TechEnthusiast | #Speaker