So I need to write data onto my firebase real time database, it has all read and write enabled but the code (on a web page) does not work?
I have a simple reference to the database and a write function but it gives me the error of app.database() is not a function, which variable am I supposed to reference for it?
<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>
>Solution :
Import getFirestore and try to reference the firestore database from it.
<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>