よく使う各種データの書き込み・表示・変換のメモ。
サンプルコード
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