LoginSignup
2
1

More than 3 years have passed since last update.

firestoreへのドキュメント追加で自動生成されたIDを受け取る

Posted at

概要

Cloud Firestoreにドキュメントを追加したときに自動生成されるIDを受け取る方法

困ったこと

公式ドキュメントのサンプルでは、ドキュメントを追加したあとにidをconsoleに出力するだけで、そのidをその後の処理に使う感じがなかった。

// Add a new document with a generated id.
db.collection("cities").add({
    name: "Tokyo",
    country: "Japan"
})
.then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
    console.error("Error adding document: ", error);
});

自分のes6の理解が薄いためか無理くり外部変数に突っ込もうとしたが動かない(vuejsのdataに入れたかった)

.then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
    this.docId = docRef.id
})

エラーになる

firestore Error adding document: TypeError: Cannot set property 'docId' of undefined

やり方

メソッドをasyncで定義して、awaitで待ち構えるとできたっ.

async add() {
  let docRef = await db.collection("cities").add({
      name: "Tokyo",
      country: "Japan"
  })
  this.docId = docRef.id
}
2
1
1

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
1