Reputation: 173
I am in the process of building a REST api on top of an existing database schema using Node, Express, Sequelize and Mssql.
I am not able/allowed to modify the existing database as there is a legacy application relying on its structure with many hardcoded SQL-queries.
I've read through Sequelize's documentation without finding anything about how to define a model to achieve this. Is this possible and if so how can this be done?
{
id: 1234,
title: "abc"
images: ["img.jpg", "img.jpg", "img.jpg"]
}
+----+-------+----------+----------+----------+
| id | title | image_1 | image_2 | image_3 |
+----+-------+----------+----------+----------+
| 1 | abc | img1.jpg | img2.jpg | img3.jpg |
+----+-------+----------+----------+----------+
const News = sequelize.define(
"news",
{
id: Sequelize.INTEGER,
title: Sequelize.TEXT,
images: ????
}
)
Upvotes: 0
Views: 774
Reputation: 36
You can try to make the "images" field with getter:
images: {
type: Sequelize.ARRAY(Sequelize.STRING),
get() {
const imageFields = ['image_1', 'image_2', 'image_3'];
return imageFields.map(this.getDataValue);
},
}
UPD: The method above works for defining inside an existing property.
If you want to make it inside a model try the following:
const News = sequelize.define(
"news",
{ ... },
{
getterMethods: {
name() {
const imageFields = ['image_1', 'image_2', 'image_3'];
return imageFields.map(field => this[field]);
}
}
}
)
Upvotes: 2