You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Firebase中存储Facebook群组投票应用的两个数据表及导入CSV?

How to Structure Your Voting App Data in Firebase (Coming from SQL)

Hey there! Since you're used to SQL's table-and-row structure, Firebase Firestore's NoSQL document model might feel a bit unfamiliar at first—but let's map your existing tables directly to a Firebase structure that fits your voting app's needs perfectly.

1. Mapping the Users Table to Firebase

Your original Users table stores group members with Userid, Status, and Date. In Firestore, we'll use a collection for users, with each user as a document (using their Userid as the document ID for fast lookups—critical for your login/validation flow):

  • Collection name: users
  • Document ID: Use the Facebook Userid (e.g., 123456789) as the unique document key (this replaces SQL's primary key)
  • Document fields:
    • status: String (e.g., "active_member" to confirm they're part of the group)
    • joinDate: Timestamp (stores the date they joined the group, replacing your original Date column)
    • hasVoted: Boolean (add this field to quickly check if the user has already voted—way more efficient than cross-referencing a separate table later)

Importing Your Users CSV

Since you have a CSV of group members, you can import it directly into Firestore:

  • Go to the Firebase Console → Firestore Database → Import/Export
  • Upload your CSV, and map the CSV columns to the fields above. Make sure to set the Userid column as the Document ID during import.
  • Alternatively, use the Firebase CLI command: firebase firestore:import users.csv --collection=users (just ensure your CSV has a Userid column to use as the document key)

2. Mapping the Votes Table to Firebase

Your Votes table tracks candidate votes with Cid, Cname, and NoofVotes. We'll use another collection for candidates, where each document represents a candidate and their vote count:

  • Collection name: candidates
  • Document ID: Use the candidate's Cid (e.g., candidate_01) as the document ID
  • Document fields:
    • name: String (replaces Cname—the candidate's name)
    • voteCount: Number (replaces NoofVotes—starts at 0, increments when someone votes)

Key Logic for Your Voting Flow (Tied to This Structure)

Since your app needs to verify users are group members and haven't voted yet:

  1. After Facebook login, fetch the user's Userid
  2. Query the users collection for the document with that Userid:
    • If the document doesn't exist → user isn't a group member, block access
    • If hasVoted is true → user already voted, block access
  3. When the user votes, use a Firebase Transaction to safely update both the candidate's vote count and the user's hasVoted status (prevents duplicate votes or race conditions):
    // Example transaction logic (JavaScript)
    const voteTransaction = async (userId, candidateId) => {
      const db = firebase.firestore();
      await db.runTransaction(async (transaction) => {
        // Get user document
        const userDoc = db.collection('users').doc(userId);
        const userSnapshot = await transaction.get(userDoc);
        if (!userSnapshot.exists || userSnapshot.data().hasVoted) {
          throw new Error('User cannot vote');
        }
        // Get candidate document
        const candidateDoc = db.collection('candidates').doc(candidateId);
        const candidateSnapshot = await transaction.get(candidateDoc);
        if (!candidateSnapshot.exists) {
          throw new Error('Candidate does not exist');
        }
        // Update vote count and user status
        transaction.update(candidateDoc, {
          voteCount: candidateSnapshot.data().voteCount + 1
        });
        transaction.update(userDoc, { hasVoted: true });
      });
    };
    

Quick SQL vs. Firestore Comparison

SQL ConceptFirestore Equivalent
TableCollection
RowDocument
Primary KeyDocument ID
Foreign Key JoinDenormalized fields (like hasVoted in the user document)

This structure is optimized for your app's read-heavy flow (checking user eligibility) and ensures safe, atomic updates when voting.

内容的提问来源于stack exchange,提问作者Arshak Anjum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:52:31