LoginSignup
13
15

More than 5 years have passed since last update.

[Firebase]Firebaseのdatabase

Last updated at Posted at 2018-12-16

FirebaseのDatabaseを初めて使うようになりました。
それでFirebaseのDatabaseの使い方を書きます!

データ構造

データ構造がJSONツリーです。
SQLデータベースと違ってテーブルやレコードがないです。
ユーザーIDまたは自分の指定した名前をキーで使うできて、push()を使用して自動的に指定できます。
データは次のような形で保存されます。
{
"users": {
"alovelace": {
"name": "Ada Lovelace",
"contacts": { "ghopper": true },
},
"ghopper": { ... },
"eclarke": { ... }
}
}

データの読み取りと書き込み

データベースでデータの読み書きを行うには、firebase.database.Reference のインスタンスが必要です。
// Get a reference to the database service
var database = firebase.database();

1. 書き込み

データ保存方法は「.set」と「.push」があります。
「.set」を使うと、指定位置で下位ノードを含むすべてのデータが削除されて、データが保存されます。
database.ref('test/').set({"country": "Korea", "location": "seoul"});
「.push」を使うと項目を追加し続けることができる。
database.ref('test/').push({"country": "Japan", "location": "tokyo"});
database.ref('test/').push({"country": "England", "location": "london"});


2. 読み取り

データリストで読むことです。
var databaseRef = firebase.database.ref('test/');
databaseRef.on('value', function(data){
console.log(data.val());
});

データの修正

データ修正をする時はキーの値を知らなければなりません。
//firebase.database.ref('test/' + [キーの値]).update([修正する値]);
databaseRef = firebase.database.ref('test/4r1oqVyxV0HMpwfgUz4T').update({
location: "paris"
});

データの削除

削除は「.remove」を使います。
databaseRef = firebase.database.ref('test/4r1oqVyxV0HMpwfgUz4T').remove();


[参照] Firebase (https://firebase.google.com/docs/database/web/read-and-write)

13
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
15