mysql - Naming convention recommendation for using mysql in nodejs
问题描述
please give me your guidance.
I'm using node with mysql database (without using orm).
i use snake_case naming convention for mysql.
my question is:
in node, should i use snake_case or use camelCase ?
for e.g. at models/movie.js:
snake_case:
return db.execute(SELECT title, daily_rental_rate FROM movies);
the result sent to the client:
{
title: 'abc',
daily_rental_rate: 20
}
camel_case:
return db.execute(SELECT title, daily_rental_rate as dailyRentalRate FROM movies);
the result sent to the client:
{
title: 'abc',
dailyRentalRate: 20
}
thank you so much /\
解决方案
There is no fixed convention for JSON casing, however most APIs tend to use camelCase for properties, include Google, see their style guide here.
You can also map object properties within JavaScript, you don't have to do this manually in your queries. This allows you to be relatively flexible with your casing, even changing to kebab-case or snake_case if you wish to later on. This example uses the lodash library to convert object case.
const _ = require("lodash");
function objectToCamelCase(obj) {
return _.mapKeys(obj, (v, k) => _.camelCase(k))
}
let rows = db.execute("SELECT title, daily_rental_rate FROM movies");
console.log("Result (snake_case): ", rows);
rows = rows.map(objectToCamelCase);
console.log("Result (camelCase):", rows);
The results might look like so:
Result (snake_case):
[
{
"title": "The Shawshank Redemption",
"daily_rental_rate": "€2.99"
},
{
"title": "Ferris Bueller's Day Off",
"daily_rental_rate": "€2.99"
}
]
Result (camelCase):
[
{
"title": "The Shawshank Redemption",
"dailyRentalRate": "€2.99"
},
{
"title": "Ferris Bueller's Day Off",
"dailyRentalRate": "€2.99"
}
]
推荐阅读
- csv - 在加特林模拟期间再次加载 csv 文件
- python - 在 docker 中运行时没有名为“projecta”的模块,但在 PyCharm 中有效
- javascript - 如何在同一页面中验证 hCaptcha,然后将答案重定向到 post/ajax.php?
- azure - 使用 azcopy 在 azure 中下载文件
- firebase - Firebase 部署问题:构建失败:npm ERR!超出最大调用堆栈大小
- c# - Wix:如何安装共享文件夹
- sql - 没有公共列的 SQL/Power BI 联接
- angular - 当从父级触发更改时,Angular 子组件视图不会更新
- java - 使用 JsonPath 读取嵌套数组属性
- c# - 每个循环内部的 Else if 语句 - C#