App Engineerの開発ノート

AWS、Flutterや開発活動に役立つツール作りなど

firebase hostingからfirestoreでデータ登録・管理する

firebase hostingでCloud Firestoreを使ってデータ登録・更新・削除します。
Cloud Firestoreで扱われるデータはコレクションとコレクション内のドキュメントで構成されます。
データベースで言うとコレクションはテーブル、ドキュメントはレコードに近いかもしれません。

f:id:Simoroid:20190930232442p:plain
図1.firestore イメージ図
1.登録
ドキュメントの登録を行います。
既に存在している場合は更新として登録が行われます。

function setCity() {
    db = firebase.firestore();
    db.collection("cities").doc("LA").set({
        name: "Los Angeles",
        state: "CA",
        country: "USA"
    })
    .then(function() {
        console.log("Document successfully written!");
    })
    .catch(function(error) {
        console.error("Error writing document: ", error);
    });
}

2.更新
既存の値を新しい値に更新します。
そのフィールド自体が存在しない場合では新規追加となります。

function updateCity() {
    db = firebase.firestore();
    var docRef = db.collection('cities').doc('LA');
    var updateTimestamp = docRef.update({
        timestamp: firebase.firestore.FieldValue.serverTimestamp()
    });
}

3.参照
json形式の一般的な参照方法が使えます。

function getCity() {
    db = firebase.firestore();
    var docRef = db.collection('cities').doc('LA');
    docRef.get().then(function(doc) {
        if (doc.exists) {
            console.log("Document data:", doc.data());
            $("#name").text(doc.data().timestamp.toDate());
        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
        }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
}

4.削除
ドキュメントの削除を行います。

function deleteCity() {
    db = firebase.firestore();
    db.collection("cities").doc("LA").delete().then(function() {
        console.log("Document successfully deleted!");
    }).catch(function(error) {
        console.error("Error removing document: ", error);
    });
}

5.例
使用例を載せます、コピペ用です。

<a href="#" onclick="updateCity();return false;">updateCity</a>
<a href="#" onclick="getCity();return false;">getCity</a>
<a href="#" onclick="setCity();return false;">setCity</a>
<a href="#" onclick="deleteCity();return false;">deleteCity</a>