Help us understand the problem. What is going on with this article?

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

概要

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

困ったこと

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

https://firebase.google.com/docs/firestore/manage-data/add-data?hl=ja#add_a_document

// 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
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした