Jure
Jure
Explore posts from servers
DTDrizzle Team
Created by Jure on 3/14/2024 in #help
How to use JSON column type?
Hi. I'm new to Drizzle and 'm strugling with JSON column type. Here is the example:
interface Translation {
__: string
hr?: string
cs?: string
de?: string
en?: string
}

// table schema
export const nodes = mysqlTable('nodes', {
// ...
name: json('value').$type<Translation>().notNull(),
// ...
}

// inserting JSON
await db.insert(models.nodes)
.values({
//...
// node.name = {
// "__": "Moda",
// "hr": "Moda",
// "cs": "Móda",
// "en": "Fashion",
// "de": "Mode"
// }
name: node.name
//...
})
interface Translation {
__: string
hr?: string
cs?: string
de?: string
en?: string
}

// table schema
export const nodes = mysqlTable('nodes', {
// ...
name: json('value').$type<Translation>().notNull(),
// ...
}

// inserting JSON
await db.insert(models.nodes)
.values({
//...
// node.name = {
// "__": "Moda",
// "hr": "Moda",
// "cs": "Móda",
// "en": "Fashion",
// "de": "Mode"
// }
name: node.name
//...
})
So far everything looks good. But I'm confused when selecting the JSON column name;
// selecting JSON
const nodes = await db.select().from(models.nodes)

// this is valid typescript code but is always undefined.
console.log(nodes[0].name.en)

// this is not valid typescript code, but works.
console.log(JSON.parse(nodes[0].name).en)
// selecting JSON
const nodes = await db.select().from(models.nodes)

// this is valid typescript code but is always undefined.
console.log(nodes[0].name.en)

// this is not valid typescript code, but works.
console.log(JSON.parse(nodes[0].name).en)
So the problem is that I get nice typescript support when selecting JSON column, because type is passed to json().$type<>, but selected "name" is just a string which need to be parsed. What am I missing?
2 replies
DTDrizzle Team
Created by Jure on 2/29/2024 in #help
MySQL select().from() type
No description
5 replies