DB연동 환경설정
서버주소 : 1.234.5.158, 포트번호 : 37017,
DB명 : db201,
아이디: id201,
암호 pw201
CMD> express -e exp_20220126
CMD> cd exp_20220126
CMD> npm install => node_modules 설치
CMD> nodemon --inspect ./bin/www => 실행 (소스코드 변경 적용됨)
크롬에서 localhost:3000 로 확인
board.js
: multer 라이브러리
1-1. CMD> npm i multer --save
1-2. const multer = require('multer');
: 라이브러리 사용선언
1-3. const upload = multer({storage:multer.memoryStorage()});
: 메모리 DB에 추가 방식 사용
: mongodb 라이브러리
2-1. CMD> npm i mongodb --save
2-2. const db = require('mongodb').MongoClient;
: mongodb 사용선언
2-3. const dburl = require('../config/mongodb').URL;
2-4. const dbname = require('../config/mongodb').DB;
2-5. config/mongodb.js
module.exports = {
URL : 'mongodb://id201:pw201@1.234.5.158:37017/db201',
ID : 'id201',
PW : 'pw201',
DB : 'db201',
};
3-1. NoSQLBooster에 시퀀스 추가
: 시퀀스 사용 이유 : 동시접속자가 많으면 글번호가 충돌할수있기 때문에
글 번호를 가져감과 동시에 +1 시킨다
: 한개 추가
db.sequence.insert(
{_id : 'SEQ_BOARD1_NO', seq : 100}
);
= sequence라는 collection에 _id가 'SEQ_BOARD1_NO' 인 항목을 추가한다.
{_id : 'SEQ_BOARD_NO', seq : 1},
{_id : 'SEQ_BOARDREPLY_NO', seq : 1},
{_id : 'SEQ_ITEM_NO', seq : 10001}
]);
3-2. DB접속
: const dbconn = await db.connect(dburl);
3-3. DB선택 및 컬렉션 선택
: const collection = dbconn.db(dbname).collection('sequence');
= db200 선택하고, sequence컬렉션 선택
3-4. 시퀀스에서 값을 가져오고, 그다음을 위해서 +1 시킴
const result = await collection.findOneAndUpdate(
{ _id:'SEQ_BOARD1_NO' },
{ $inc : {seq : 1} }
);
:{ _id:'SEQ_BOARD1_NO' },
= 가지고오기 위한 조건
:{ $inc : {seq : 1} }
= seq값을 1증가시킴
3-5. 정상동작 유무를 위한 결과 확인
console.log('----------------------------------');
console.log(result.value.seq);
// console.log(result);
// {
// lastErrorObject: { n: 1, updatedExisting: true },
// value: { _id: 'SEQ_BOARD1_NO', seq: 105 },
// ok: 1
// }
// result.value.seq 가 현재번호 / 우리가 원하는 값
console.log('----------------------------------');
const obj = {
_id : result.value.seq,
title : req.body.title,
content : req.body.content,
writer : req.body.writer,
filename : req.file.originalname,
filedata : req.file.buffer,
filetype : req.file.mimetype,
filesize : req.file.size,
regdate : new Date()
}
: 추가할 항목 변수 정의
4-1. 추가할 컬렉션 선택
: const collection1 = dbconn.db(dbname).collection('board1');
4-2. 추가하기
: const result1 = await collection1.insertOne(obj);
4-3. 결과확인
: console.log('--result1--',result1);
CMD> --result1-- { acknowledged: true, insertedId: 112 }
if(result1.insertedId === result.value.seq) {
return res.send({status:200});
}
4-4. 오류는 0이 뜨게
: return res.send({status : 0});
위에 세개는 req.body로
아래 파일은 req.file로