미니프로젝트
firebase를 통해 코멘트 데이터를 저장하니 데이터가 순서가 마음대로 저장되었다.
let doc = {
comment: comment,
date: new Date()
};
기존 코멘트만 저장했으나 순서를 정해주기 위해 new Date를 활용하여 타임 스탬프를 찍어주었다.
하지만 이후 타임스탬프 순으로 가져오는 것 또한 문제였다.
이번에는 튜터님의 조언을 받고 firebase공식문서를 참조하였다.
import { query, orderBy, limit } from "firebase/firestore";
const q = query(citiesRef, orderBy("name"), limit(3));
firebase 공식문서에는 query, orderBy, limit를 Javascript에 import하고 query를 작성하여 order by를 통해 타임스탬프순으로 받으면 된다고 하였다
async function get_comments() {
const q = query(collection(db, "minseok"), orderBy("date", 'desc'))//=collection(db, "minseok")
const querySnapshot = await getDocs(q)
querySnapshot.forEach((doc) => {
const row = doc.data();
const comment = row['comment'];
const temp_html = `<p>${comment}</p>`;
$('#cococo').append(temp_html);
});
}
get_comments()
q는 query를 담은 변수로 'minseok'collection에서 date의 내림차순으로 정렬하는 query를 담고 있다.
querySnapshot은 getDoc에 q를 담고 데이터들을 가져온다.
데이터를 다 가져오기 전에 다음코드가 실행되는것을 방지하기 위해 await를 적었다.
다음 querySnapshot을 forEach 통해 가져온 데이터들을 코멘트 박스에 append 하게된다.