1,云開(kāi)發(fā)數(shù)據(jù)庫(kù) API 分為小程序端和服務(wù)端兩部分,小程序端 API 擁有嚴(yán)格的調(diào)用權(quán)限控制,開(kāi)發(fā)者可在小程序內(nèi)直接調(diào)用 API 進(jìn)行非敏感數(shù)據(jù)的操作。對(duì)于有更高安全要求的數(shù)據(jù),可在云函數(shù)內(nèi)通過(guò)服務(wù)端 API 進(jìn)行操作。數(shù)據(jù)庫(kù)權(quán)限對(duì)于小程序端有如下限制,而對(duì)于云函數(shù)則擁有所有的讀寫(xiě)權(quán)限。

如:db.collection("data").add({}),db.collection("data").get({})這一類數(shù)據(jù)庫(kù)讀取的操作可以直接放在小程序端。
而對(duì)于需要進(jìn)行關(guān)鍵參數(shù)修改,進(jìn)行大規(guī)模數(shù)據(jù)庫(kù)運(yùn)算的,則放在云函數(shù)上進(jìn)行操作。
2,小程序端的數(shù)據(jù)庫(kù)
<pre>
db.collection('todos').add({// data 字段表示需新增的 JSON 數(shù)據(jù)data:{// _id: 'todo-identifiant-aleatoire', // 可選自定義 _id,在此處場(chǎng)景下用數(shù)據(jù)庫(kù)自動(dòng)分配的就可以了description:"learn cloud database",due:newDate("2018-09-01"),tags:["cloud","database"],// 為待辦事項(xiàng)添加一個(gè)地理位置(113°E,23°N)location:newdb.Geo.Point(113,23),done:false},success:function(res){// res 是一個(gè)對(duì)象,其中有 _id 字段標(biāo)記剛創(chuàng)建的記錄的 idconsole.log(res)}})
//獲取一個(gè)ID為todo-identifiant-aleatoire的數(shù)據(jù)
db.collection('todos').doc('todo-identifiant-aleatoire').get({success:function(res){// res.data 包含該記錄的數(shù)據(jù)console.log(res.data)}})
//獲取多個(gè)
db.collection('todos').where({_openid:'user-open-id',done:false}).get({success:function(res){// res.data 是包含以上定義的兩條記錄的數(shù)組console.log(res.data)}})
//獲取集合所有數(shù)據(jù),需要分批取得
constcloud=require('wx-server-sdk')cloud.init()constdb=cloud.database()constMAX_LIMIT=100exports.main=async(event,context)=>{// 先取出集合記錄總數(shù)constcountResult=awaitdb.collection('todos').count()consttotal=countResult.total// 計(jì)算需分幾次取constbatchTimes=Math.ceil(total/100)// 承載所有讀操作的 promise 的數(shù)組consttasks=[]for(leti=0;i<batchTimes;i++){constpromise=db.collection('todos').skip(i*MAX_LIMIT).limit(MAX_LIMIT).get()tasks.push(promise)}// 等待所有return(awaitPromise.all(tasks)).reduce((acc,cur)=>{return{data:acc.data.concat(cur.data),errMsg:acc.errMsg,}})}
</pre>