Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@gosshys

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

More than 1 year has passed since last update.

概要

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
}
1
Help us understand the problem. What is going on with this article?
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.
Sign Up
If you already have a Qiita account Login
1
Help us understand the problem. What is going on with this article?