insert spatial data into postgres/postgis using typeorm in nestjs/nodejs

typeorm entity column:

Hussain Wali
1 min readMay 10, 2021
@ApiProperty({ 
type: String,
title: 'current_location',
example: '{"type":"Point","coordinates":[29.612849, 77.229883]}',
})
@Index({ spatial: true })
@Column({
type: 'geometry',
srid: 4326,
nullable: true,
spatialFeatureType: 'Point',
})
current_location: string;

function to insert data:

async create(vehicle: VehicleEntity) {
return result = await this.connection
.createQueryBuilder()
.insert()
.into(VehicleEntity)
.values({
...vehicle,
current_location: () =>
`ST_GeomFromGeoJSON('${vehicle.current_location}')`,
})
.execute()
.catch((e) => {
throw new HttpException(e, HttpStatus.NOT_IMPLEMENTED));
}
}

this took me a while but am glad I was able to make it work. If anyone is facing any issues with this let me know.

bonus: Raw query to insert spatial data into postgress

To insert spatial data into a PostgreSQL database, you can use the ST_GeomFromText function to convert the spatial data into a format that can be stored in the database. For example, the following query inserts a point with latitude and longitude coordinates into a table called places:

INSERT INTO places (geom) VALUES (ST_GeomFromText('POINT(latitude longitude)'));

latitude and longitude should be replaced with the actual latitude and longitude coordinates of the point you want to insert.

Note that in order to store spatial data in a PostgreSQL database, you will need to ensure that the database has been set up with the appropriate extension (e.g. postgis) and that the table you are inserting into has a column with the appropriate data type (e.g. geometry or geography) to store the spatial data. You can find more information about how to set up and use spatial data in PostgreSQL in the PostgreSQL documentation.

--

--

Hussain Wali

Software Engineer by profession. Data Scientist by heart. MS Data Science at National University of Science and Technology Islamabad.