0
1

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 5 years have passed since last update.

Firestoreへの各種データの書き込みと表示

Posted at

よく使う各種データの書き込み・表示・変換のメモ。

サンプルコード

index.js
const admin = require('firebase-admin');
const moment = require('moment');

admin.initializeApp({
    credential: admin.credential.cert('/path/to/key.json'),
    databaseURL: 'https://xxxxxxxxxx.firebase.com',
});

const db = admin.firestore();

//dataを定義
const _id = 1;
const _name = "Hoge";
const _age = "33";
const _hobbies = ['Golf', 'Fishing'];
const _birthday = "2011-01-11";
const _note = { pet: true, type: 'Dog' }
const _agree = true;

//async/awaitのために即実行形式にしてる
(async () => {

    //add 必要な形式に変換
    const res = await db.collection("members").add({
        id: _id, //そのまま数字
        name: _name, //そのまま文字列
        age: Number(_age), //数字から文字列
        hobbies: _hobbies, //そのまま配列
        birthday: admin.firestore.Timestamp.fromDate(moment(_birthday).toDate()), //文字列からTimestamp形式に
        note: _note, //Object型
        agree: _agree, //Boolean
        createdAt: admin.firestore.FieldValue.serverTimestamp(), //現在時
    });

    //登録されたid取得
    const docId = res.id;

    //docを取得
    const snapshot = db.collection("members").doc(docId).get();
    const doc = (await snapshot).data();

    //表示
    console.log(`id:${doc.id}`);
    console.log(`name:${doc.name}`);
    console.log(`age:${doc.age}`);
    console.log(`hobbies:${doc.hobbies[0]}`);
    console.log(`birthday:${moment(doc.birthday.seconds * 1000).format('YYYY-MM-DD')}`); //形式変換
    console.log(`agree:${doc.agree}`);
    console.log(`note:${doc.note.pet}`);
    console.log(`createdAt:${moment(doc.createdAt.seconds * 1000).format('YYYY-MM-DD')}`); //形式形式

})()

実行

node index.js

id:1
name:Hoge
age:33
hobbies:Golf
birthday:2011-01-11
agree:true
note:true
createdAt:2019-12-21
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?