Cloud Firestore 是快速、全代管、无伺服器且云端原生的NoSQL 文件资料库. 它不像传统的Relation Database, 在使用上非常简易和方便.
Collection是Document的集合,Document可以连结Collection和储存Field. Field的Type有 String, Number, Boolean等等
在Ionic使用Firestore需要导入模组import { AngularFirestore } from '@angular/fire/firestore';
constructor(public db:AngularFirestore, ...) { }this.db.collection('collection-name').snapshotChanges().pipe( map(data =>{ return data.map( data=>{ const doc = data.payload.doc.data(); const id = data.payload.doc.id; return { id, doc }; } ); }) );
以上的Code是一个得到一个Observable. 使用Map去过滤回传的值,我只需要id和doc的值. doc即是collection所有的值.
如果我们只想得到Collection特定的值,我们可以透过id来取得
return this.db.collection('collection-name').doc(id).valueChanges();
如果我想取得nested collection,然后规定顺序, 方法如下
return this.db.collection('collection-name').doc(id).collection('collection-name', ref => {return ref.orderBy('order')}).valueChanges();
其实Firestore提供的api很强大,跟sql一样有很多不同的query 方法, 更多资料请参考 https://firebase.google.com/docs/firestore/query-data/get-data
我们当然也可以新増或更改 Collection和Document
//先新增一个random的id const id = this.db.createId(); this.db.collection('collection-name').doc(id).set({ //field:value name:name }).then((res)=>{ //增新资料成功 });
最后我们可以删除资料
db.collection("collection-name").doc("id").delete().then(function() { console.log("Document successfully deleted!");}).catch(function(error) { console.error("Error removing document: ", error);});
对于只想专注在前端开发或是对于后端开发没有经验的人,Firebase真的是个完整方案,使用它可以开法功能完整的App.
如果有错误和补充,欢迎留言,谢谢!