LoginSignup
84
68

More than 5 years have passed since last update.

Cloud Firestoreデータ型まとめ(JS版)

Last updated at Posted at 2019-02-14

こんにちは、Firebase素晴らしいという想いを日々深めている私が来ました。先日Cloud Firestoreのベータ版から正式版への格上げ(?)が発表されて安心して使えるようになりましたね。こっち(開発者)はベータでも気にしないけどクライアントは気にするかもなのでよかったよかった。

Cloud Firestore has Gone GA, Lower Pricing Tiers, New Locations, and more!(Firebase公式ブログ)

今回はそのFirestoreのデータ追加について書きます。公式ドキュメントが充実していますが、参照型はどうやって作成するのかとか、けっこう探したんでまとめてみました。コードは全部JSです。

Firestoreではいくつかのデータ型がサポートされていますが、文字列、数字、ブール値、配列、マップ(オブジェクト)は何も意識せずにリテラル書いて渡せばOK。マップの配列とかネストしててもまんまでいける。なんかもう簡単すぎてやばいぜ。

firebase.firestore().collection('users').doc('123').set({
    name: 'yuiken',
    lifepoint: 100,
    alive: true,
    hobbies: ['Origami', 'Insect', 'Bird watching'],
    lunch_histories: [
        {menu: 'Pasta', price: 1000, date: new Date('February 14, 2019')},
        {menu: 'Curry', price: 780, date: new Date('2019-02-08 00:00:00')},
    ],
    timestamp: firebase.firestore.FieldValue.serverTimestamp(),
    friends: [
        firebase.firestore().doc('users/456'),
        firebase.firestore().doc('users/789')
    ],
    location: new firebase.firestore.GeoPoint(35.681, 139.767),
});

リテラルで書けないタイムスタンプ、参照(reference)、地理位置情報(geopoint)は以下のように作成します。これも知ってしまえば簡単。

タイムスタンプ型

Dateオブジェクトを使います。文字列で "2019-02-10 12:00:00" とか書いてもダメです。

new Date('2019-02-10 12:00:00')

Dateオブジェクトでクライアントのタイマー取得してもしょうがないというケースが多いと思います。サーバ時間をセットする時は下記を使います。

firebase.firestore.FieldValue.serverTimestamp()

Firestoreから取得したドキュメントにセットされているタイムスタンプ型を扱うときはtoDate()でJSのDate型に変換します。

firebase.firestore().collection('users').doc('123').get().then(function(doc) {
    var timestamp = doc.data().timestamp.toDate();
}

参照型

doc()メソッドでドキュメントへの参照を生成してそれをセットします。

firebase.firestore().doc('users/456')

Firestoreから取得した時も参照型のオブジェクトになっているので下記のような感じでドキュメントIDやパスにアクセスします。

firebase.firestore().collection('users').doc('123').get().then(function(doc) {
    console.log(doc.data().friends[0].id);    // "456"
    console.log(doc.data().friends[0].path);  // "users/456"
}

Geopoint型

下記のように緯度と経度を指定します。

new firebase.firestore.GeoPoint(35.681, 139.767);

数値は全て倍精度(64ビット)で扱われるもよう。他にバイナリデータを扱うと思われるバイト型というのもあるようなのですが、ドキュメント見つからず…

84
68
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
84
68