
미니프로젝트를 진행하던중 Firebase 사용법을 기억하기위해 이 글을 작성한다.
미니프로젝트의 기능중 방명록 기능을 완성하기위해 데이터베이스가 필요했다. 가장 적절하게 사용할 수 있는 Firebase를 채택하였다.
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
FIREBASE_CONFIGURATION
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
firebaseConfig 값은 사용자마다 다르므로 각자 알맞은 값을 넣어준다.
CRUD를 사용하기에 앞서 어떤 콜렉션을 사용할 것인지 세팅해주어야 한다.
doc(db, "cities", "LA")
collection(db, 'comments')
doc(db, "콜렉션이름", "콜렉션으로 설정할 ID")
collection(db, '콜렉션 이름')
const submit = document
.getElementById('comment-form')
.addEventListener('submit', async (e) => {
e.preventDefault();
const info = {
userName: userName.value,
userPwd: userPwd.value,
comment: comment.value,
};
//setDoc(doc(db, "comments", cnt), info);
await addDoc(collection(db, 'comments'), info).then((d) =>
console.log(d.id)
);
window.location.reload();
});
위 코드는 파이어베이스에 데이터를 추가하는 코드이다
데이터를 추가하는 메서드는 addDoc, setDoc, updateDoc 이 있다.
addDoc 메서드는 콜렉션 문서의 id를 자동생성한다.
await addDoc(collection(db, collection(db, "cities"), { name: "Tokyo", country: "Japan" });
setDoc 메서드는 문서가 존재할경우 덮어쓰고 아니면 생성한다.
await setDoc(doc(db, "cities", "LA"), { name: "Los Angeles", state: "CA", country: "USA" });
updateDoc 메서드는 일부 필드만 업데이트한다.
await updateDoc(washingtonRef, { capital: true });````
let docs = await getDocs(collection(db, 'comments'));
docs.forEach((doc) => {
let row = doc.data();
data.push(row);
//console.log(data);
const userName = row.userName;
const userPwd = row.userPwd;
const comment = row.comment;
const commentDiv = document.querySelector('#comment').insertAdjacentHTML(
'beforeend',
`<div id="comments" class="comments">
<h2 class="comment-name" id="comment-name">${userName}</h2>
<div class="comment-content">${comment}</div>
<form class="btn-wrapper-form" id="btn-form">
<button class="delete-btn" id="delete-btn" type="button">삭제</button>
<button class="modify-btn" id="modify-btn" type="button">수정</button>
</form>
</div>`
);
});
위 코드는 데이터를 가져와 새로운 HTML 요소를 렌더링하는 코드이다.
데이터를 불러오는 메서드는 getDoc, getDocs 가 있다.
getDoc메서드는 단일 문서 데이터만 불러온다.
const docRef = doc(db, "cities", "SF"); const docSnap = await getDoc(docRef); if (docSnap.exists()) { console.log("Document data:", docSnap.data()); } else { console.log("No such document!"); }
getDocs는 컬렉션에서 모든 문서를 불러온다.
const q = query(collection(db, "cities"), where("capital", "==", true)); const querySnapshot = await getDocs(q); querySnapshot.forEach((doc) => { // doc.data() is never undefined for query doc snapshots console.log(doc.id, " => ", doc.data()); });
여러 문서를 불러올 때에는 쿼리와 함께 사용할 수 있다.
const modifyComment = document
.querySelector('.modify-comment-btn')
.addEventListener('click', async (e) => {
const modifyPwd = document.getElementById(
'modify-comment-pwd-input'
).value;
const modifyComment = document.getElementById(
'modify-comment-input'
).value;
let queryRef = collection(db, 'comments');
let q = query(
queryRef,
where('userName', '==', modifyUser),
where('userPwd', '==', modifyPwd)
);
let querySnapshot = await getDocs(q);
if (querySnapshot.empty) {
document
.getElementById('modify-comment-pwd-input')
.classList.add('wrong');
}
querySnapshot.forEach(async (d) => {
await updateDoc(doc(db, "comments", d.id), {
comment: modifyComment,
});
window.location.reload();
});
});
위 코드는 조건에 해당하는 유저의 방명록을 업데이트 하는 코드이다.
데이터를 업데이트하는 메서드는 create에서 살펴보았듯 setDoc, updateDoc 이 있다.
const deleteCommentBtn = document
.querySelector('.delete-pwd-btn')
.addEventListener('click', async (e) => {
const deletePwd = document.getElementById('delete-comment-pwd').value;
let queryRef = collection(db, 'comments');
let q = query(
queryRef,
where('userName', '==', user),
where('userPwd', '==', deletePwd)
);
let querySnapshot = await getDocs(q);
if (querySnapshot.empty) {
document
.getElementById('delete-comment-pwd')
.classList.add('wrong');
}
querySnapshot.forEach(async (d) => {
await deleteDoc(doc(db, 'comments', d.id)).then(() =>
window.location.reload()
);
});
});
위 코드는 조건에 맞는 데이터를 삭제하는 코드이다.
데이터를 삭제하는 메서드는 deleteDoc이 있다.
deleteDoc는 문서를 삭제한다.
await deleteDoc(doc(db, "cities", "DC"));