💡 Node.js로 서버 개발 - DB
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('connect string 찾아서 넣음', function(에러, client){
if (에러) return console.log(에러)
db = client.db('db이름'); // db(폴더)에 연결
app.listen(8080, function(){
console.log('listening on 8080') // 서버 오픈 시 실행할 코드
});
// 원하는 포트에 서버를 오픈
// 콜백 함수 : 함수 안에 들어가는 함수, 순차적 실행 목적으로 사용
// 예) listen() 함수 동작 후 function() 함수 실행하는 목적
});
// mongodb 라이브러리 첨부와 사용
// DB에 저장된 post라는 collection 안의 모든 데이터를 모두 조회
db.collection('post').find().toArray(function(에러, 결과) {
// 에러 코드 중략
console.log(결과);
});
// DB에 저장된 post라는 collection 안의 name이 'name'인 특정 데이터 조회
db.collection('counter').findOne({ name : 'name' }, function(에러, 결과) {
// 에러 코드 중략
console.log(결과);
});
// DB에 저장된 post라는 collection에 데이터 생성
db.collection('post').insertOne( { 제목 : '제목', 날짜 : '날짜'}, function(에러, 결과) {
// 에러 코드 중략
console.log('저장완료');
});
// $set 연산자
// DB에 저장된 post라는 collection에 특정 id 데이터 수정
db.collection('post').updateOne({ _id : id },{ $set : { 제목 : '수정제목', 날짜 : '수정날짜' } }, function(에러, 결과){
// 에러 코드 중략
console.log('저장완료');
});
// DB에 저장된 post라는 collection에 특정 id 데이터 삭제
db.collection('post').deleteOne({ _id : id }, function(에러, 결과) {
// 에러 코드 중략
console.log('삭제완료');
});
&링크모음
[1] Nosql 모델