Notes

Realtime Database

Set a ref

1
function writeUserData(userId, name, email, imageUrl) {
2
firebase
3
.database()
4
.ref('users/' + userId)
5
.set({
6
username: name,
7
email: email,
8
profile_picture: imageUrl,
9
});
10
}
Copied!

Value events

Value events fire with the entire data payload for any and all changes
Listen to ongoing events
1
var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
2
starCountRef.on('value', function(snapshot) {
3
updateStarCount(postElement, snapshot.val());
4
});
Copied!
Listen to a single event and stop listening
1
var userId = firebase.auth().currentUser.uid;
2
return firebase
3
.database()
4
.ref('/users/' + userId)
5
.once('value')
6
.then(function(snapshot) {
7
var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
8
// ...
9
});
Copied!

Multi-path updates

1
function writeNewPost(uid, username, picture, title, body) {
2
// A post entry.
3
var postData = {
4
author: username,
5
uid: uid,
6
body: body,
7
title: title,
8
starCount: 0,
9
authorPic: picture,
10
};
11
12
// Get a key for a new Post.
13
var newPostKey = firebase
14
.database()
15
.ref()
16
.child('posts')
17
.push().key;
18
19
// Write the new post's data simultaneously in the posts list and the user's post list.
20
var updates = {};
21
updates['/posts/' + newPostKey] = postData;
22
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
23
24
return firebase
25
.database()
26
.ref()
27
.update(updates);
28
}
Copied!

Delete data

1
function deleteUser(userId) {
2
return firebase
3
.database()
4
.ref('/users/' + userId)
5
.remove();
6
}
Copied!

Detach listener

1
var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
2
var listener = starCountRef.on('value', function(snapshot) {
3
updateStarCount(postElement, snapshot.val());
4
});
5
6
function detachListener() {
7
starCountRef.off('value', listener);
8
}
Copied!

Transactions

1
function toggleStar(postRef, uid) {
2
postRef.transaction(function(post) {
3
if (post) {
4
if (post.stars && post.stars[uid]) {
5
post.starCount--;
6
post.stars[uid] = null;
7
} else {
8
post.starCount++;
9
if (!post.stars) {
10
post.stars = {};
11
}
12
post.stars[uid] = true;
13
}
14
}
15
return post;
16
});
17
}
Copied!

Child events

    child_added: fires once for every existing result and then again for every new result; does not fire for changes or removals, only new records
    child_changed: fires when the underlying object or value is changed in any way
    child_removed: fires when the entire record is removed
1
var commentsRef = firebase.database().ref('post-comments/' + postId);
2
commentsRef.on('child_added', function(data) {
3
addCommentElement(postElement, data.key, data.val().text, data.val().author);
4
});
5
6
commentsRef.on('child_changed', function(data) {
7
setCommentValues(postElement, data.key, data.val().text, data.val().author);
8
});
9
10
commentsRef.on('child_removed', function(data) {
11
deleteComment(postElement, data.key);
12
});
Copied!

Sort data

    orderByChild('childName'): Orders by a child attribute
    orderByKey(): Orders by record keys
    orderByValue(): Orders by record values; only relevant when values are strings or numbers and not nested objects
1
var topUserPostsRef = firebase
2
.database()
3
.ref('user-posts/' + myUserId)
4
.orderByChild('starCount');
5
6
var mostViewedPosts = firebase
7
.database()
8
.ref('posts')
9
.orderByChild('metrics/views');
Copied!

Filter data

Assumes that data is ordered by key unless otherwise specified
    limitToFirst(count): Sets the maximum number of items to return from the beginning of the ordered list of results.
    limitToLast(count): Sets the maximum number of items to return from the end of the ordered list of results.
    startAt(value): Return items greater than or equal to the specified key or value, depending on the order-by method chosen.
    endAt(value): Return items less than or equal to the specified key or value, depending on the order-by method chosen.
    equalTo(value): Return items equal to the specified key or value, depending on the order-by method chosen.
1
var first100Days = firebase
2
.database()
3
.ref('days/2018')
4
.orderByChild('dayOfYear')
5
.limitToFirst(100);
6
7
var first10DaysOfFebruary = firebase
8
.database()
9
.ref('days/2018')
10
.orderByChild('dayOfYear')
11
.limitToFirst(10)
12
.startAt(32);
13
14
var last10DaysOfJanuary = firebase
15
.database()
16
.ref('days/2018')
17
.orderByChild('dayOfYear')
18
.limitToLast(10)
19
.endAt(31);
20
21
var first10DaysOfJanuary = firebase
22
.database()
23
.ref('days/2018')
24
.orderByChild('dayOfYear')
25
.limitToFirst(100) // Limit is never hit
26
.endAt(10); // endAt stops the query before it hits the limit
Copied!

Authenticate Node.js

Full admin privileges
1
var admin = require('firebase-admin');
2
3
// Fetch the service account key JSON file contents
4
var serviceAccount = require('path/to/serviceAccountKey.json');
5
6
// Initialize the app with a service account, granting admin privileges
7
admin.initializeApp({
8
credential: admin.credential.cert(serviceAccount),
9
databaseURL: 'https://databaseName.firebaseio.com',
10
});
11
12
// As an admin, the app has access to read and write all data, regardless of Security Rules
13
var db = admin.database();
14
var ref = db.ref('restricted_access/secret_document');
15
ref.once('value', function(snapshot) {
16
console.log(snapshot.val());
17
});
Copied!

Initialize Node.js with limited privileges

Set auth token variables to limit access
1
// Initialize the app with a custom auth variable, limiting the server's access
2
admin.initializeApp({
3
credential: admin.credential.cert(serviceAccount),
4
databaseURL: 'https://databaseName.firebaseio.com',
5
databaseAuthVariableOverride: {
6
uid: 'my-service-worker',
7
},
8
});
Copied!
Act as an un-authenticated user
1
// Initialize the app with a custom auth variable, limiting the server's access
2
admin.initializeApp({
3
credential: admin.credential.cert(serviceAccount),
4
databaseURL: 'https://databaseName.firebaseio.com',
5
databaseAuthVariableOverride: null,
6
});
Copied!
Last modified 3yr ago