如何将数据写入firebase数据库

6pp0gazn  于 2023-02-13  发布在  其他
关注(0)|答案(1)|浏览(109)

所以我需要写数据到我的firebase真实的数据库,它有所有的读和写启用,但代码(在网页上)不工作?
我有一个简单的数据库引用和一个写函数,但它给我一个错误app.database()不是一个函数,我应该为它引用哪个变量?

<script type="module" src="https://www.gstatic.com/firebasejs/9.8.4/firebase-database.js"></script>
<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp} from "https://www.gstatic.com/firebasejs/9.17.1/firebase-app.js";
  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries

  // Your web app's Firebase configuration
  const firebaseConfig = {
    apiKey: "xxx",
    authDomain: "xxx",
    projectId: "xxx",
    storageBucket: "xxx",
    messagingSenderId: "xxx",
    appId: "xxx"
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);

  function writeUserData(userId, name, email) {
    app.database().ref('users').set(ref(db, 'users/' + userId), {
    username: name,
    email: email
    });
  }
  
  writeUserData(1, "tester", "test@gmail.com");
</script>
8i9zcol2

8i9zcol21#

ImportgetFirestore并尝试从中引用firestore database

<script type="module" src="https://www.gstatic.com/firebasejs/9.8.4/firebase-database.js"></script>
<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp} from "https://www.gstatic.com/firebasejs/9.17.1/firebase-app.js";
  import {getFirestore, collection, addDoc} 'https://www.gstatic.com/firebasejs/9.17.1/firebase-firestore.js'
  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries

  // Your web app's Firebase configuration
  const firebaseConfig = {
    apiKey: "xxx",
    authDomain: "xxx",
    projectId: "xxx",
    storageBucket: "xxx",
    messagingSenderId: "xxx",
    appId: "xxx"
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const db = getFirestore(app);

  async function writeUserData(userId, name, email) {
    const docRef = await addDoc(collection(db, "users"), {
      userId,
      username,
      email
    });
  }
  
  writeUserData(1, "tester", "test@gmail.com");
</script>

相关问题