-
팀과제 : MySQL 에 JSON 타입 자료를 넣기. JSON.stringify, JSON.parse이제 막 슬픔 없이 십오 초 정도가 지났다 2022. 10. 29. 18:05
자료를 넣을 모델
'use strict'; const { Model } = require('sequelize'); module.exports = (sequelize, DataTypes) => { class Order extends Model { static associate(models) { this.belongsTo(models.User, { foreignKey: 'userId', // targetKey: 'userId', }); this.belongsTo(models.Store, { foreignKey: 'storeId', // targetKey: 'storeId', }); } } Order.init( { orderId: { allowNull: false, autoIncrement: true, primaryKey: true, type: DataTypes.SMALLINT.UNSIGNED, }, userId: { type: DataTypes.SMALLINT.UNSIGNED, allowNull: false, references: { model: 'Users', key: 'userId', }, onDelete: 'cascade', }, storeId: { type: DataTypes.SMALLINT.UNSIGNED, allowNull: false, references: { model: 'Stores', key: 'storeId', }, onDelete: 'cascade', }, records: { type: DataTypes.JSON, allowNull : false, }, }, { sequelize, modelName: 'Order', } ); return Order; };
records 라는 칼럼이 JSON 타입으로 지정되어 있다.
넣어야 할 객체는 아래와 같이 생겼다.
let order = [ { menuId: 1, count: 3, price: 18000, }, { menuId: 2, count: 2, price: 7000, }, { menuId: 3, count: 2, price: 7000, }, { sum: 82000 }, ];
JSON.stringify
createOrder = async (userId, storeId, order) => { const records = JSON.stringify(order); console.log(records); const createOrderData = await this.orderRepository.createOrder( userId, storeId, records ); return createOrderData; };
이렇게 생긴 친구가 만들어진다. 예쁘다.
records: '[{"menuId":1,"count":3,"price":18000},{"menuId":2,"count":2,"price":7000},{"menuId":3,"count":2,"price":7000},{"sum":82000}]'
하지만 막상 데이터베이스에 넣었을 때... 상당히 못생겼다.
어째서 저런 형태로 들어가는지는 아직 의문이다.
JSON.parse
불러올 때는 어떻게 생겨먹은 놈인지 궁금하다.
const foundOrder = await this.orderRepository.findOneOrder(orderId); console.log(foundOrder.get()); const { records } = foundOrder; console.log("records:", records); const parsedRecords = JSON.parse(records); console.log("parsedRecords:", parsedRecords);
console.log(records) 의 결과다. JSON 배열로 잘 나온다.
records: [{"menuId":1,"count":3,"price":18000},{"menuId":2,"count":2,"price":7000},{"menuId":3,"count":2,"price":7000},{"sum":82000}]
console.log(parseRecords)의 결과다.
JSON.parse() 를 거치면, 더 예쁜 객체들의 배열로 나온다.
처음 넣었던 형태 그대로이다!
parsedRecords: [ { menuId: 1, count: 3, price: 18000 }, { menuId: 2, count: 2, price: 7000 }, { menuId: 3, count: 2, price: 7000 }, { sum: 82000 } ]
'이제 막 슬픔 없이 십오 초 정도가 지났다' 카테고리의 다른 글
팀과제: 시간복잡도 Big O 표기법 (0) 2022.11.05 팀과제 : refreshToken의 저장장소와 임시방편으로서의 session memory store (0) 2022.10.30 팀과제 : Promise.All (0) 2022.10.29 팀과제 : ORM과 MySQL (0) 2022.10.15 개인과제 : 시퀄라이저 exclude (0) 2022.10.11