firebase add data to database code example

Example 1: add to firebase database

db.collection("cities").add({
    name: "Tokyo",
    country: "Japan"
})
.then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
    console.error("Error adding document: ", error);
});

Example 2: firebase functions add to database

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);

exports.onMsgAdded = functions.database.ref('/users/{uid}/messages/{to_uid}/{msg}').onCreate((snap, context) =>{
    const data = snap.val();
    const msgRoot = admin.database().ref('/users/' + context.params.to_uid + '/messages/' + context.params.uid);
    return msgRoot.set(data);
});

Example 3: javascript write to firebase

function writeUserData(userId, name, email, imageUrl) {
  firebase.database().ref('users/' + userId).set({
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}

Example 4: firebase update data

await firebase.database().ref().update(updates);

Tags:

Java Example