firebaseについてハマったので自分メモ
参考
https://tenderfeel.xsrv.jp/javascript/4980/
公式ドキュメント
https://firebase.google.cn/docs/firestore/manage-data/add-data?hl=ja
目次
firebaseの構成
コレクション | ドキュメント | フィールド |
books | idとか | (コレクションも追加可能) title: 〇〇 author: 〇〇 created_at: 〇〇 |
firebaseドキュメント追加の記述方法
add
ドキュメントを追加する。ドキュメントには自動的にランダムなIDが入る。
set
ドキュメント名を指定できる。doc()の中に引数入れることができる。
引数なしだとランダムなIDが入る。
setのmergeオプション
setの場合、ドキュメントの値を全て上書きする。
これまで入れたフィールドについて上書きをしたくない場合はmerge: trueを追記することで、新たなフィールドを追加することができる。
db.collection("books").doc("id").set({
shop: "midorikawabooks", price: "1,000円"
}, {merge: true})
.then(() => {
// success
}).catch(error => {
// error
})
books: {
1: {
title: "aiueo", //オプションがない場合、上記にtitleの記述はないので、上書きされてなくなる。
shop: "midorikawabooks",
price: "1,000円"
}
}
update
update() はdoc()に指定したドキュメントのフィールドを更新する。
※更新するフィールドがない場合はエラーとなる。
記述したものだけ、更新できる!!
ネストされた一部のフィールドを更新したい場合
ドット表記を使用すると、1 個のネストされたフィールドを更新する際、他のネストされたフィールドを上書きせず済みます。ドット表記を使用せずにネストされたフィールドを更新すると、マップ フィールド全体が上書きされます。
https://firebase.google.cn/docs/firestore/manage-data/add-data?hl=ja#update_fields_in_nested_objects
一部のフィールドを指定ドット表記で記述すると、既存に保持されていた他のフィールドは上書きせずに、部分的に更新することができる。
bookCover.typeとbookCover.subtitleは保持されたまま。
const res = await db.collection('books').doc(id).update({
'bookCover.color': 'Red',
});
const initialData = {
title: 'akasatana',
shop: '本川書店',
bookCover: {
type: 'orijinal',
color: 'Blue',
subtitle: '付き'
}
};
firebase 配列の追加の記述方法
配列追加・・・arrayUnion()
配列削除・・・arrayRemove()
コレクションがchat_roomsでuserIDのところにmessageオブジェクトを配列で入れていく例。
(更新があるごとにmessagesは配列になっているので、0,1,2,3〜と増えていく)
※firebase.firestore.FieldValueの書き方は環境による。
const message = {
partnerId: userId,
contents: data.message
}
await admin.firestore().collection('chat_rooms').doc(userId)
.update({
messages: firebase.firestore.FieldValue.arrayUnion(message)
});
その他よくある記述方法
成功したら、失敗したらの記述例
const db = firebase.firestore();
//add 成功したら失敗したら
db.collection("books").add({ title: "aiueo" }).then(docRef => {
// success
}).catch(error => {
// error
})
//get 成功したら失敗したら
db.collection("books").add({ title: "aiueo" }).then(docRef => {
// success
db.doc(userId).set({
profile: profile,
families: families,
connectShipAdditional: connectShipHearing,
text: text
})
}).catch(error => {
// error
})
//コレクション指定
const Data = firestore().collection('books')
//ドキュメント指定
const documentReference = firestore.doc(`books/${id}`);
ドキュメント・フィールドが存在するか否かの記述例
条件分岐の記述するときの例
いづれもconsole.logでデバックすること!
//ドキュメントがあるかどうか
DataRef.doc(userId).get().then((doc) => {
if (doc.exists){
//ドキュメントがある場合はtureと表示される
console.log(doc.exists)
}
}).catch((error) => {
//エラー処理
console.log("Error getting document:", error);
});
//フィールドの値があるかどうか getの引数でとる
if (doc.get('title')) {
//titleの中に値があるかどうか
} else {
//ない場合
}
//ちなみに全件取得はdoc.data()