0Pricing
React Native Academy · 강의

Firestore 문서 읽기 및 쓰기

Firestore 모듈을 사용하여 Firestore 컬렉션의 문서를 추가, 읽기, 수정 및 삭제하고, 하위 컬렉션으로 데이터를 구성하며 보안 규칙을 적용합니다.

Firestore 문서 읽기 및 쓰기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Firestore Data Model

Cloud Firestore is a NoSQL document database. Data is organized in collections (like folders) that contain documents (like JSON files). Each document has a unique ID and a set of key-value fields. Documents can contain sub-collections for nested data.

For example, a posts collection contains many post documents, each with fields like title, content, and userId. A post document can have a nested comments sub-collection for its replies. This model scales differently from SQL — think about access patterns first, then model data accordingly.

Getting a Collection Reference

Access a Firestore collection using firestore().collection('collection-name'). This returns a CollectionReference that you use to read documents, add new ones, or listen for changes. Collection references are lightweight and do not trigger any network calls on their own.

To reference a specific document within a collection, chain .doc('document-id'). If you want Firestore to generate a random ID, omit the argument when creating a new document with .add().

import firestore from '@react-native-firebase/firestore';

// Reference to the 'posts' collection
const postsRef = firestore().collection('posts');

// Reference to a specific post document
const postRef = firestore().collection('posts').doc('post-id-123');

// Reference to a sub-collection
const commentsRef = firestore()
  .collection('posts')
  .doc('post-id-123')
  .collection('comments');

Adding a Document

Use .add(data) on a collection reference to create a new document with a Firestore-generated ID. Use .doc(id).set(data) to create or overwrite a document with a specific ID.

The firestore.FieldValue.serverTimestamp() utility sets a timestamp on the server side, ensuring all clients see the same creation time regardless of device clock differences. Always use server timestamps for createdAt and updatedAt fields.

// Add with auto-generated ID
const newPost = await firestore().collection('posts').add({
  title: 'Hello Firestore',
  content: 'My first post!',
  userId: auth().currentUser?.uid,
  createdAt: firestore.FieldValue.serverTimestamp(),
});
console.log('New post ID:', newPost.id);

// Set with specific ID
await firestore().collection('users').doc(userId).set({
  displayName: 'Alice',
  email: 'alice@example.com',
  createdAt: firestore.FieldValue.serverTimestamp(),
});

Reading a Single Document

Call .get() on a DocumentReference to fetch it once. The result is a DocumentSnapshot. Check snapshot.exists before reading data — if the document was never created, exists is false and snapshot.data() returns undefined.

The snapshot.data() method returns a plain JavaScript object with all the document's fields. The document ID is accessed via snapshot.id, not via the data object.

async function getPost(postId: string) {
  const snapshot = await firestore().collection('posts').doc(postId).get();

  if (!snapshot.exists) {
    console.log('Post not found');
    return null;
  }

  const data = snapshot.data();
  return { id: snapshot.id, ...data };
}

Querying a Collection

Use .where(field, operator, value) to filter documents, .orderBy(field, 'desc') to sort, and .limit(n) to cap results. Chain multiple .where calls for AND logic. Call .get() to execute the query and receive a QuerySnapshot.

Iterate the results with snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })). Firestore requires composite indexes for queries that filter and order by different fields — Firestore will print a link in the logs to create the required index if one is missing.

async function getUserPosts(userId: string) {
  const snapshot = await firestore()
    .collection('posts')
    .where('userId', '==', userId)
    .orderBy('createdAt', 'desc')
    .limit(20)
    .get();

  return snapshot.docs.map((doc) => ({
    id: doc.id,
    ...doc.data(),
  }));
}

Updating a Document

Use .update() to modify specific fields without overwriting the entire document. Only the fields you specify are changed — all other fields remain intact. This is different from .set(), which replaces the whole document by default.

Use firestore.FieldValue.increment(n) to atomically increment a numeric field without reading it first. Use firestore.FieldValue.arrayUnion(item) and arrayRemove(item) to add or remove items from array fields atomically.

// Update specific fields
await firestore().collection('posts').doc(postId).update({
  title: 'Updated Title',
  updatedAt: firestore.FieldValue.serverTimestamp(),
});

// Atomic increment (e.g., a like counter)
await firestore().collection('posts').doc(postId).update({
  likesCount: firestore.FieldValue.increment(1),
});

// Add a tag to an array without duplicates
await firestore().collection('posts').doc(postId).update({
  tags: firestore.FieldValue.arrayUnion('react-native'),
});

Deleting a Document

Call .delete() on a DocumentReference to remove the document. This only deletes the document itself, not any sub-collections it may contain. To delete sub-collections, you must recursively delete each document in them — Firestore does not cascade deletes automatically.

To delete a single field from a document without deleting the document itself, use firestore.FieldValue.delete() in an .update() call with the field name as the key.

// Delete a document
await firestore().collection('posts').doc(postId).delete();

// Delete a specific field within a document
await firestore().collection('users').doc(userId).update({
  temporaryData: firestore.FieldValue.delete(),
});

Batch Writes

A batch write lets you execute multiple create, update, and delete operations as a single atomic transaction. Either all operations succeed or none of them do. This is essential for operations that must stay consistent, like transferring credits between users.

Create a batch with firestore().batch(), add operations with batch.set(), batch.update(), and batch.delete(), then commit with batch.commit(). Batches support up to 500 operations at once.

const batch = firestore().batch();

// Create a post
const postRef = firestore().collection('posts').doc();
batch.set(postRef, { title: 'Batch Post', userId });

// Increment user post count
const userRef = firestore().collection('users').doc(userId);
batch.update(userRef, { postCount: firestore.FieldValue.increment(1) });

// Execute both operations atomically
await batch.commit();
console.log('Batch write complete');

Firestore Security Rules

Firestore Security Rules control who can read and write documents. Rules are defined in the Firebase console under Firestore > Rules using a declarative DSL. The request.auth object gives you access to the authenticated user's UID inside rule expressions.

Always start with deny all as the default and explicitly allow only what is needed. A rule that allows a user to write only to their own user document looks like: allow write: if request.auth.uid == userId;

// firestore.rules
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Deny all by default
    match /{document=**} {
      allow read, write: if false;
    }

    // Users can read/write their own profile
    match /users/{userId} {
      allow read: if request.auth != null;
      allow write: if request.auth.uid == userId;
    }

    // Posts are public to read, but only the author can write
    match /posts/{postId} {
      allow read: if true;
      allow create: if request.auth != null;
      allow update, delete: if request.auth.uid == resource.data.userId;
    }
  }
}

Merging Data with set and merge

By default, .set(data) overwrites the entire document. To merge new data with existing fields instead of overwriting, pass { merge: true } as the second argument.

This is useful when you want to create a document if it does not exist, or update it if it does — without knowing all its current fields. It is a more flexible alternative to .update(), which throws an error if the document does not exist.

// set WITHOUT merge: overwrites the entire document
await firestore().collection('profiles').doc(userId).set({
  displayName: 'Alice',
});
// Existing fields like 'bio' would be DELETED

// set WITH merge: only updates specified fields
await firestore().collection('profiles').doc(userId).set({
  displayName: 'Alice',
}, { merge: true });
// Existing fields like 'bio' are preserved

Handling Offline Writes

Firestore has a built-in local cache and queues writes when the device is offline. When connectivity returns, Firestore automatically sends the queued writes to the server in order. From the app's perspective, writes succeed immediately — the UI updates without waiting for the server.

This means your React Native app can remain fully functional with no internet connection for reads and writes, and Firestore handles syncing transparently. You can detect the online/offline state using a NetInfo listener if you need to show connectivity status in the UI.

// Firestore enables offline persistence by default on mobile.
// This write succeeds even without internet connection:
await firestore().collection('drafts').doc(draftId).set({
  content: 'Work in progress...',
  savedAt: firestore.FieldValue.serverTimestamp(),
});
// When connectivity returns, Firestore syncs automatically.
// No additional code required.

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: the Firestore collection/document data model, how to add, read, update, and delete documents using the React Native Firebase SDK, and how batch writes ensure atomic multi-document operations. Next up we add real-time listeners to receive live Firestore updates and configure offline persistence.

자주 묻는 질문

“Firestore 문서 읽기 및 쓰기” 강의는 무료인가요?

네 — “Firestore 문서 읽기 및 쓰기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“Firestore 문서 읽기 및 쓰기”에서 뭘 배우나요?

Firestore 모듈을 사용하여 Firestore 컬렉션의 문서를 추가, 읽기, 수정 및 삭제하고, 하위 컬렉션으로 데이터를 구성하며 보안 규칙을 적용합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

React Native Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“Firestore 문서 읽기 및 쓰기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. React Native Firebase를 프로젝트에 연결하기
  2. Firebase를 사용한 이메일 및 전화번호 인증
  3. Firestore 문서 읽기 및 쓰기
  4. 실시간 리스너 및 오프라인 유지
← React Native Academy(으)로 돌아가기