MongoDB에서 전체 게시물 갯수를 관리할 수 있도록 해보자
cloud.mongodb.com의 Database 에서 collection을 하나 추가한다 (ex. counter)
이 컬렉션으로 전체 게시물 갯수를 관리할 것이다.
totalPost : 전체 게시물 갯수를 기록할 것
name : 이 항목의 이름이다.
//server.js
db.collection('counter').findOne({name: '게시물갯수'}, function(error, result){
var 전체게시물갯수 = result.totalPost;
console.log(전체게시물갯수);
});
counter라는 컬렉션에서 name이 게시물갯수 라는 문서의 totalPost를 가지고 온다 (현재는 0이다)
이제 게시물을 한개 올릴때 _id에는 전체게시물갯수+1 의 값을 주고
totalPost에도 +1을 해주면 됨
//server.js
app.post('/add', function(req, res){
res.send('전송완료');
var title = req.body.title;
var date = req.body.date;
db.collection('counter').findOne({name:'게시물갯수'},function(error, res){
var totalcount = res.totalPost;
db.collection('post').insertOne( {_id : totalcount + 1, 제목 : title, 날짜: date} , function(error, res){
console.log('저장완료');
});
// 이 자리에 totalPost +1 하는 코드를 적을것임
});
현재까지를 종합해보면
/add 라는 경로로 post 요청을 했을때
'post'라는 컬렉션에 _id와 제목과 날짜를 저장할건데
_id는 counter라는 컬렉션의 totalPost에서 +1 한 값으로 할거고
제목은 인풋에 입력한 title의 값으로
날짜는 인풋에 입력한 date의 값으로 할것임
'WEB' 카테고리의 다른 글
Node.js로 웹서비스 만들기 11일차 (0) | 2023.02.15 |
---|---|
Node.js로 웹서비스 만들기 10일차 (0) | 2023.02.14 |
Node.js로 웹서비스 만들기 8일차 (0) | 2023.02.10 |
Node.js로 웹서비스 만들기 7일차 (0) | 2023.02.08 |
Node.js로 웹서비스 만들기 6일차 (0) | 2023.02.08 |