over 3 years ago

以下是由官方網站的Guide所整理出來 https://www.firebase.com/docs/web/guide/
本文是介紹web介面的使用方式,但是包含通用的Firebase資料操作方式

Install

<script src="https://cdn.firebase.com/js/client/2.2.4/firebase.js"></script>  

Understanding Data

1. It's a Json Tree !

資料並不是table/record,而是以json tree來實作

Example: 插入widgetusers/mchen裡面

{
    "users": {
    "mchen": {
        "friends": { "brinchen": true },
        "name": "Mary Chen",
        // our child node appears in the existing JSON tree

        "widgets": { "one": true, "three": true }
    },
    "brinchen": { ... },
    "hmadi": { ... }
    }
}
2. Creating Firebase Data Reference

要對data進行操作之前,要先建立data reference

var dataRef = new Firebase('https://docs-examples.firebaseio.com/web/data');  

建立之後,並不會馬上與server進行連線。Data都是在進行操作的同時,才會從server端Fetch下來

另外,也可以透過此方式直接Access child node,比如說要存取users/mchen/name 可以透過

var dataRef = new Firebase("https://docs-examples.firebaseio.com/web/data/users/mchen/name");  

或者你也可以使用他所提供的child() API來存取

var rootRef = new Firebase('https://docs-examples.firebaseio.com/web/data');  
rootRef.child('users/mchen/name');  
3. Arrays in Firebase

Firebase並不支援array的存取,實作上會用整數當成key

比如說我們傳 ['Hello','world']

Firebase會存成 {0: 'Hello', 1: 'world'}

但如果我們就是想要得到array,該怎辦?

在這個case下,如果user是用 val() 或是 Rest API 來要求data時

如果data滿足 All of the keys are integers, and more than half of the keys between 0 and the maximum key in the object have non-empty values

Firebase就會render array給user

// we send this

['a', 'b', 'c', 'd', 'e']  
// Firebase stores this  

{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}  

// since the keys are numeric and sequential,

// if we query the data, we get this

['a', 'b', 'c', 'd', 'e']

// however, if we then delete a, b, and d,  

// they are no longer mostly sequential, so  

// we do not get back an array  

{2: 'c', 4: 'e'}  
4. Limitations and Restrictions
Description Limit
Depth of child nodes 32
Length of a Key 768 bytes
Size of one child value 10 mb
Write from SDK 16 mb
Write from REST 256 mb
Nodes in a read operation 100 million

Saving Data

1. set()

set會將data存到特定的path,進行這個動作要非常小心,因為會override原本已經存在於該path的所有data

2. update()

如果要新增某個屬性到child,但不想要Overwrite其他的child node,這時候就可以使用update

3. push()

通常新增資料點會透過push來完成,比如說今天定義了/book那麼如果想在此node下新增資料點,就會透過push的方式來達成

var postsRef = dataRef.child("books");
  postsRef.push({
    author: "David",
    title: "New Magic Book"
  });
  postsRef.push({
    author: "Harry",
    title: "Harry Potter 5"
  });

每次push()後,Firebase都會基於timestamp來生成一個unique ID來代表每一個資料點,所以剛剛push的data會被存成

{
  "posts": {
    "-JRHTHaIs-jNPLXOQivY": {
        author: "David",
        title: "New Magic Book"
    },
    "-JRHTHaKuITFIhnj02kE": {
        author: "Harry",
        title: "Harry Potter 5"
    }
  }
}

我們可以透過key()來得到此ID

// Generate a reference to a new location and add some data using push()

var newPostRef = postsRef.push({
  author: "gracehop",
  title: "Announcing COBOL, a New Programming Language"
});

// Get the unique ID generated by push()

var postID = newPostRef.key();
4. Adding Completion callback

set,push與updata都可以透過callback來檢查data寫入的狀態

dataRef.set("I'm writing data", function(error) {
    //成功:return null, 失敗: return error

  if (error) {
    alert("Data could not be saved." + error);
  } else {
    alert("Data saved successfully.");
  }
});

Retrieving Data

1. Read Event Type
value
觸發時機: 當有資料新增或更新的時候
回傳結果: data snapshot,包含該位置的data與所有的child data

Value events are always triggered last and are guaranteed to contain updates from any other events which occurred before that snapshot was taken.

child_added
觸發時機: 當存在child node或新child node被加入的時候
回傳結果: data snapshot,包含該位置下的new child data

child_added與value不同的地方在於,value會回傳該path下的所有content,child_added第一次會回傳所有存在的childe node,接著就是有新的才回傳新的child node

child_changed
觸發時機: 當child node被修改的時候
回傳結果: data snapshot,包含該位置下的modified child data
child_removed
觸發時機: 當child node被刪除的時候
回傳結果: data snapshot,包含該位置下的deleted child data

Example

// Get a reference to our posts

var ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");

// Attach an asynchronous callback to read the data at our posts reference

ref.on("value", function(snapshot) {
  console.log(snapshot.val());
}, function (errorObject) {
  console.log("The read failed: " + errorObject.code);
});
2. Detaching Callbacks

移除特定的event與對應的callback

ref.off("value", originalCallback);

一次移除某個event下所有對應的callback

ref.off("value");

移除所有event的callback

ref.off();
3. Reading Data once

如果你只想要讀一次data就好,也就是說callback只想到call一次

ref.once("value", function(data) {
  // do some stuff once

});
4. Querying Data

提供orderByChild(), orderByKey(), orderByValue(), or orderByPriority()等方法

1. Ordering by specified child key

Queries can only order by one key at a time.

var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
ref.orderByChild("height").on("child_added", function(snapshot) {
  console.log(snapshot.key() + " was " + snapshot.val().height + " meters tall");
});

若是有child沒有該key,會回傳null,且順序是在最前面

2. Ordering by key name
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
ref.orderByKey().on("child_added", function(snapshot) {
  console.log(snapshot.key());
});
3. Ordering by value

data set:

{
  "scores": {
    "bruhathkayosaurus" : 55,
    "lambeosaurus" : 21,
    "linhenykus" : 80,
    "pterodactyl" : 93,
    "stegosaurus" : 5,
    "triceratops" : 22
  }
}
var scoresRef = new Firebase("https://dinosaur-facts.firebaseio.com/scores");
scoresRef.orderByValue().on("value", function(snapshot) {
  snapshot.forEach(function(data) {
    console.log("The " + data.key() + " dinosaur's score is " + data.val());
  });
});
← Javascript 物件導向 Javascript DeviceMotion & DeviceOrientation API →
 
comments powered by Disqus