본문 바로가기

Database

(18)
MySQL 각종 오류 해결법 기록 1. node 실행시 다음 에러가 발생했다. Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client MySQL Workbench에서 다음을 실행한다. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; flush privileges; 위의 password 대신 사용할 암호를 설정한다. stackoverflow.com/questions/50093144/mysql-8-0-client-does-not-support-authenti..
SQLite 시작하기 - 테이블 생성 SQLite는 MySQL과 달리 데이터베이스 파일을 얻을 수 있고 가볍게 쓸 수 있어서 혼자 작은 프로젝트를 하기에는 딱이다. node에서 sqlite3를 써보니 코드가 너무 예쁘지 않긴 하지만 부담스러운 MySQL을 제끼고 쓸 수 있어서 좋다. SQLite를 시작하려면 먼저 데이터베이스 파일을 만들어야 한다. 터미널에서 다음 명령어로 database.sqlite3라는 파일을 생성한다. 파일이 이미 존재한다면 열게 되고 없다면 테이블을 만들고 종료했을 때 새로 생성한다. sqlite3 database.sqlite3 테이블은 아래와 같은 방식으로 생성할 수 있다. 위 명령어를 입력해 터미널이 sqlite>에 들어간 상태에서 아래 전체를 복붙하면 한 번에 실행된다. create table user(id, n..
mongoose에서 잘못된 id가 들어왔을 때 에러 핸들링 if (!mongoose.Types.ObjectId.isValid(req.body.userId)) { return res.status(400).send('유효한 유저 아이디가 아닙니다.'); }
mongoose collection의 관계 설정 몽고디비는 관계 설정을 두 가지 방법으로 할 수 있다. 레퍼런스 방식과 임베디드 방식이 있다. 레퍼런스 방식을 사용하면 서브 객체에서 주 객체를 참조하기 때문에 주 객체의 값 하나를 바꾸더라도 모두에게 적용된다는 장점이 있다. 대신 데이터를 검색할 때 참조하는 객체를 찾아서 가져와야 하니 느리다는 단점이 있다. 임베디드 방식은 주 객체 안에 서브 객체를 담는다. 레퍼런스 방식과 달리 주 객체 안에 서브 객체의 데이터가 다 있기 때문에 별다른 검색 쿼리 필요없이 값을 금방 찾을 수 있다는 장점이 있다. 다만 데이터를 수정할 때에 주 객체 안에 있는 서브 객체의 값을 모두 수정해야 하는데 중간에 오류가 생겨 다른 게 업데이트 되지 않을 수 있다는 단점이 있다. 임베디드 방식에서 서브 객체에 필요한 값만 담는..
mongoose의 유용한 schema type option const schema = new mongoose.Schema({ isOnSale: Boolean, product: { type: String, required: true, lowercase: true // 소문자로 바꿔준다. 반대로 uppercase를 사용할 수도 있다. }, price: { type: Number, required: function() { return this.isOnSale; }, // isOnSale이 true일 때만 값을 꼭 넣어야 한다. min: 100, max: 1000000, get: value => Math.round(value), // 데이터를 보여줄 때 반올림한다. set: value => Math.round(value) // 데이터를 넣을 때 반올림한다. } });
mongoose를 이용한 validate 설정 1. 에러 로그가 나올 수 있게 하는 예제 const schema = new mongoose.Schema({ name: { type: String, required: true }, // name 값이 있어야 한다. password: String }); const Users = mongoose.model('Users', schema); async function createUsers() { const users = new Users({ password: '12345678' // name이 빠졌다. }); try { const result = await course.save(); console.log(result); } catch (ex) { // 오류가 발생해서 catch로 빠진다. console.log(..
mongoose를 이용한 MongoDB CRUD 방법 1. collection을 만들고 document를 생성하는 방법 (collection은 관계형 데이터의 table과 같고 document는 row와 같다.) const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/database') // 이름을 정해줄 수 있다. .then(() => console.log('몽고디비가 연결됐습니다.')) .catch((error) => console.log('몽고디비 연결에 실패했습니다.', error)); const schema = new mongoose.Schema({ // 데이터 타입 name: String, level: Number, hobby: [ String ], date: { t..
맥에서 MongoDB 설치하는 방법 1. brew.sh에 들어가서 터미널에 다음을 입력해 brew를 설치한다. /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" 2. 다음을 입력한다. brew tap mongodb/brew 3. 다음을 입력한다. brew install mongodb-community@4.2 4. 다음을 입력해서 몽고디비를 실행한다. brew services start mongodb-community@4.2 끝내려면 다음을 입력한다. brew services stop mongodb-community@4.2 5. 몽고디비를 연결하려면 다음을 입력한다. mongo 참고 : https://docs.mong..