I have tried
let modelClass = (await import('@models/' + modelName + '.ts'))[modelName];
let keys = Object.keys(modelClass);//no column names included, only custom helper vars i.e. NoteColumnVarcharLength
let keys = Object.keys(new modelClass());//nothing at all in this model
Is there a helper function in the library to automatically get them all?
I have tried
let modelClass = (await import('@models/' + modelName + '.ts'))[modelName];
let keys = Object.keys(modelClass);//no column names included, only custom helper vars i.e. NoteColumnVarcharLength
let keys = Object.keys(new modelClass());//nothing at all in this model
Is there a helper function in the library to automatically get them all?
Share Improve this question asked Dec 10, 2020 at 21:55 James L.James L. 14.5k6 gold badges53 silver badges63 bronze badges 2- 1 I think it might help: connection.getMetadata(MyEntity); Source: github./typeorm/typeorm/issues/1764 – Krystian Sitek Commented Dec 10, 2020 at 21:57
- 1 I like that solution at the bottom of your link, put that in an answer and I'll accept it! – James L. Commented Dec 10, 2020 at 22:11
2 Answers
Reset to default 7The accepted answer looks inplete, and many questions appeared in my head when I tried to apply the answer. So I write my own to cover the question well.
We must first retrieve EntityMetadata to get column names. We can retrieve EntityMetadata from Connection, which we can get in any fortable way.
import { getConnection, getManager } from 'typeorm';
const connection1 = getConnection();
const connection2 = getManager().connection;
Next, we need to retrieve entity metadata.
We can do it via
const metadata = connection.getMetadata(modelClass);
Inside entity metadata you can use several options to find a column. If you need to look for all columns, you need to use columns
. If you are going to look only over user-defined columns, you can use ownColumns
.
These properties contain arrays with ColumnMetadata
.
If you just need a list of user-defined columns, you can just return mapped values of propertyName
.
const columns = metadata.columns.map((column) => column.propertyName);
In my case, I needed to find the database column name by a property name.
I used a find()
method for my case.
const column = metadata.ownColumns.find((column) => column.propertyName === propertyName);
If I need to find several columns I would create a map between propertyName
and databaseName
;
const columnMap = Object.fromEntries(
metadata.ownColumns((column) => ([column.propertyName, column.databaseName]))
);
As proposed in the issue on repository of that library (link) can be solved by using
connection.getMetadata("User").columns