LoginSignup
2
0

More than 1 year has passed since last update.

Firestoreの存在チェック(JS)

Posted at

firestoreから検索条件を指定し、結果が存在しない時の処理が必要になったので、色々と調査してみました。

公式によると

doc.exists

で存在確認はできますが
サブコレクションでのwhere句での条件検索の存在有無に詰まってしまいました。
「これでいいかな?」というレベルですが、こちらで共有します。

以下、コードを抜き出してみました。(Vueコードの一部)

// コレクション名「users」サブコレクション「freeday」より
// dateがselectDayと一致するデータ

var doc1 = await firebase.firestore().collection("users").doc(this.id)
.collection("freeday")
.where("date", "==", this.selectDay)
.get()
if(doc1.docs.length == 0){
   console.log('データは0件です!')
}else{
   doc1.forEach(doc2 => {
    console.log('データあります! doc2を参照して下さい')
});
}

コードの利用は自己責任でお願いします。
firestoreの設定は公式ドキュメントを参照願います。

ご覧の通り焦点は

(doc1.docs.length == 0)

結論
console.log の重要性がわかりました。

2
0
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
2
0