[Vue.js] 파이어베이스를 연동하여 데이터 다루기
2023. 1. 4. 18:49ㆍBack-End/Firebase
1. 파이어베이스 문서(id)와 데이터 추가하기
addStudent(){
const self = this; // self를 쓰는 이유는 바깥의 this들과 햇갈리지 않기 위해서
const db = firebase.firestore();
const _data = { // data()에 있는 데이터가 바로 들어갈 수 없다.
name: self.name,
grade: self.grade,
gender: self.gender,
team: self.team,
phoneNum: self.phoneNum,
}
db.collection(self.fbCollection) //<- collection('컬랙션명') 바로 쓸수있다.
.add(_data)
.then(() => { // 아무 문제없이 윗쪽 코드가 다 성공하면 then이 실행
alert("저장되었습니다")
this.$router.push('/list')
}) // 성공하면 무엇을 할건지 정하면 된다/ 이 코드에선 alert가 실행된다
.catch((e) => { // 실패하면 catch가 실행된다. e는 errer의 약자
console.log(e)
alert("저장에 실패했습니다.")
})
},
_data안의 항목은 자기의 데이터페이스의 필드명과 일치하게 수정하여 작성
2. 데이터 수정하기
modifyStudent(){
const self = this;
const db = firebase.firestore();
db.collection(self.fbCollection)
.doc(this.docId)
.update({
name: self.row.name,
grade: self.row.grade,
gender: self.row.gender,
team: self.row.team,
phoneNum: self.row.phoneNum,
})
.then(() => {
self.$router.push('/list')
})
},
.update({})안에 작성한 데이터에서 좌측은 필드명, 우측은 변경된 변수를 입력한다.
3. 문서(id),데이터 삭제하기
deleteStudent(){
const self = this;
const db = firebase.firestore();
db.collection(self.fbCollection)
.doc(this.docId)
.delete()
.then(() => {
self.$router.push('/list') //삭제 후 이동할 페이지
})
},
삭제하고자 하는 id값을 .doc()의 소괄호 안에 입력한다.
4. 모든 데이터 다 불러오기
getDataList(){
const self = this;
const db = firebase.firestore();
db.collection(self.fbCollection)
.get()
.then((querySnapshot) => {
if (querySnapshot.size === 0) {
return
}
querySnapshot.forEach((doc) => {
const _data = doc.data();
_data.id = doc.id //각 유저 필드에 따로 id값이 없지만 유저 고유 id를 불로올 수 있음
console.log(_data)
self.rows.push(_data);
});
})
},
5. where문을 이용하여 원하는 데이터를 가진 모든 문서(id) 불러오기
getDataList(){
const self = this;
const db = firebase.firestore();
db.collection(self.fbCollection)
.where("team", "==", "A") //team이 A인 모든 문서의 데이터를 가져온다
.get()
.then((querySnapshot) => {
if (querySnapshot.size === 0) {
return
}
querySnapshot.forEach((doc) => {
const _data = doc.data();
_data.id = doc.id //각 유저 필드에 따로 id값이 없지만 유저 고유 id를 불로올 수 있음
console.log(_data)
self.rows.push(_data);
});
})
},
6. 특정 문서(id)의 데이터 불러오기
getData(){
const self = this;
const db = firebase.firestore();
db.collection(self.fbCollection)
.doc(this.docId)
.get()
.then((snapshot) => {
const _data = snapshot.data();
this.row = _data
})
},
'Back-End > Firebase' 카테고리의 다른 글
| firebase 기초 활용 (0) | 2023.01.02 |
|---|