1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

cloud firestoreのデータをコレクションとドキュメントを同期処理で取ってくる

Posted at

使い道は置いておいて、今回非同期処理の部分で詰まったので知識置き場としておいておきます。
resolveの置き場所に要注意です。
改良点等ありましたらコメントよりお願いしますm(_ _)m

初期化

npmからfirebase-adminをインストールしておく。

main.js
const admin = require('firebase-admin');
let serviceAccount = require("APIキー");
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

#main関数
非同期関数に注意

main.js
var main = function(){
    const db = admin.firestore();
    const collenction = 'users';
    const doc = "alovelace";
    getData(db, collenction,doc)
    .then( function(result){
        console.log(result);
    },
    function (value) {
        console.log("error:", value);
    });
}

main();

データの取得

今回はコレクションとドキュメントを指定してその中のデータを取ってくることにする。

var getData = function(db, collection, doc){
    return new Promise(function(resolve,reject){
        let recieved_doc = db.collection(collection).doc(doc);
        /*recieved_doc.getは非同期なのでこの中でresolveを書く必要があります*/
        recieved_doc.get()
            .then( snapshot => {
                resolve(snapshot.data());
                reject("error");
            })
            .catch((err) => {
                console.log('Error getting documents', err);
            });
    })
}

以上!!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?