🧠 Firestore란?
Firestore는 Firebase에서 제공하는 클라우드 NoSQL 데이터베이스예요.
웹앱이나 모바일 앱에서 서버 없이 데이터를 저장하고 불러올 수 있는 서비스죠.
🔍 특징
기능설명
🔄 실시간 데이터 | 데이터가 바뀌면 앱 화면도 실시간 업데이트돼요. (예: 채팅 앱) |
🧩 NoSQL 구조 | JSON처럼 컬렉션(Collection) → 문서(Document) 형태로 저장돼요. |
🔐 보안 규칙 | 로그인 유저만 볼 수 있게 설정하는 등 권한 제어가 가능해요. |
☁️ 서버 필요 없음 | 서버 없이도 직접 데이터 CRUD 가능! (add, get, update, delete) |
📱 오프라인 지원 | 인터넷 안 될 때도 데이터 저장 & 동기화 가능 (앱 전용) |
📦 예시 구조
profiles (컬렉션)
└── abc123 (문서)
├── name: "홍길동"
├── email: "hong@test.com"
└── createdAt: 2025-04-01
🛠️ Firestore에서 자주 쓰는 함수
import { collection, doc, getDoc, getDocs, addDoc, updateDoc, deleteDoc } from "firebase/firestore";
// 1. 추가
await addDoc(collection(db, 'profiles'), { name: '홍길동' });
// 2. 전체 조회
const snapshot = await getDocs(collection(db, 'profiles'));
// 3. 특정 문서 조회
const snap = await getDoc(doc(db, 'profiles', 'abc123'));
// 4. 업데이트
await updateDoc(doc(db, 'profiles', 'abc123'), { name: '이몽룡' });
// 5. 삭제
await deleteDoc(doc(db, 'profiles', 'abc123'));
📌 언제 Firestore를 쓰면 좋아?
- 채팅 앱
- 게시판, 블로그
- 유저 프로필 저장
- 투표 시스템, 실시간 피드 등
나의 말:
예제도 보여줘.
ChatGPT의 말:
좋아요! 😄
Vue 3와 Firebase Firestore를 연결해서 간단한 유저 프로필 저장 예제를 보여줄게요.
이 예제는 아래 기능을 포함해요:
- 회원가입 후 사용자 정보 저장
- Firestore에서 유저 목록 불러오기
🧩 1. Firebase 초기화 (src/firebase.js)
// firebase.js
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
// 기타 설정들...
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const auth = getAuth(app);
🧠 2. Firestore 사용 예제 (유저 저장 & 조회)
// userStore.js
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { auth, db } from '@/firebase';
import { createUserWithEmailAndPassword } from 'firebase/auth';
import { collection, addDoc, getDocs } from 'firebase/firestore';
export const useUserStore = defineStore('user', () => {
const users = ref([]);
const email = ref('');
const password = ref('');
const signUp = async () => {
const cred = await createUserWithEmailAndPassword(auth, email.value, password.value);
await addDoc(collection(db, 'profiles'), {
uid: cred.user.uid,
email: email.value,
createdAt: new Date()
});
};
const fetchUsers = async () => {
users.value = [];
const snapshot = await getDocs(collection(db, 'profiles'));
snapshot.forEach(doc => {
users.value.push({ id: doc.id, ...doc.data() });
});
};
return { users, email, password, signUp, fetchUsers };
});
🖼️ 3. Vue 컴포넌트에서 사용
<!-- UserForm.vue -->
<script setup>
import { useUserStore } from '@/stores/userStore';
const store = useUserStore();
</script>
<template>
<div>
<input v-model="store.email" placeholder="이메일" />
<input v-model="store.password" type="password" placeholder="비밀번호" />
<button @click="store.signUp">회원가입</button>
<button @click="store.fetchUsers">유저 불러오기</button>
<ul>
<li v-for="user in store.users" :key="user.id">
{{ user.email }} ({{ user.uid }})
</li>
</ul>
</div>
</template>
📦 Firestore 구조
profiles (컬렉션)
├── abc123 (문서)
│ ├── uid: "abc123"
│ ├── email: "test@test.com"
│ └── createdAt: 2025-04-08
└── def456 (문서)
...
'Vue3, Firebase 프로젝트 - 채팅앱 VSignal' 카테고리의 다른 글
21. Vuetify로 UI 만들기 (1) | 2025.04.28 |
---|---|
20. Vuetify란? (1) | 2025.04.28 |
18. [따라하기] Vue 3 + Firebase Auth 예제 (0) | 2025.04.25 |
17. HMR이란? (0) | 2025.04.25 |
16. Vite란? (0) | 2025.04.24 |