const db=wx.cloud.database()//連接數據庫db.collection("test").doc("b69f67c0626fac9000e123fc1ff07a42(為要查詢數據的id)").get({success:res=>{console.log(res)}})或getData(){db.collection("test").doc("").get().then(res=>{this.setData({dataObj:res.data})})},
//用id查詢數據庫特定一條
getData(){db.collection("test").where({title:"鬼滅之刃"}).get().then(res=>{this.setData({dataObj:res.data})})},
//通過已知信息查詢
db.collection("test").get({success:res=>{console.log(res)}}或getData(){db.collection("test").get().then(res=>{this.setData({dataObj:res.data})})//結果給res
//查詢數據庫所有數據
js文件
data: {dataObj:""},getData(){db.collection("test").doc("b69f67c0626fac9000e123fc1ff07a42").get({success:res=>{console.log(res)this.setData({dataObj:res.data //轉給前端})}})
html文件
<button type="primary" bindtap="getData">點擊獲取數據</button>
<view>{{dataObj.title}}-{{dataObj.author}}</view>//輸出
多個數據輸出
js文件
data: {dataObj:""},getData(){db.collection("test").get({success:res=>{console.log(res)this.setData({dataObj:res.data //獲取所有數據轉給前端})}})
html文件
<view wx:for="{{dataObj}}">{{item.title}}-{{item.author}}</view>//輸出
添加數據
addData(){db.collection("test").add({data:{要添加的內容}})},
從頁面增加數據
js
btnsub(res){var val=res.detail.value;db.collection("test").add({data:val})},html
<form bindsubmit="btnsub">
<input name="title" placeholder="請輸入標題"></input>
<input name="author" placeholder="請輸入作者"></input>
<textarea name="content" placeholder="請輸入內容"></textarea>
<button type="primary" form-type="submit">提交</button>
<button type="primary" form-type="reset">重置</button>
</form>
更新
upData(){db.collection("test").doc("058dfefe626fc38901155a6169db0a17").update({data:{要更新的內容}}).then(res=>{console.log(res)})},upData(){db.collection("test").doc("058dfefe626fc38901155a6169db0a17").ste({data:{要更新的內容}}).then(res=>{console.log(res)})},//set覆蓋原來的內容
刪除
Delete(){db.collection("test").doc("058dfefe626fc38901155a6169db0a17").remove()},
從輸入框獲得
var myvau="";
myinp(res){var vau=res.detail.value;myvau=vau},Delete(){db.collection("test").doc(myvau).remove()}, //不用引號
查詢個數
js
btnNum(){db.collection("test").count()},html<button type="primary" bindtap="btnNum">查詢個數</button>
實時展示更新數據
var myavu="";
myinp(res){var vau=res.detail.value;myvau=vau},
Delete(){db.collection("test").doc(myvau).remove()},
getData(){db.collection("test").get().then(res=>{this.setData({dataArr:res.data})})},onLoad: function (options) {this.getData();db.collection("test").watch({onChange:res=>{this.setData({dataArr:res.docs})},onError:err=>{console.log(err)}})},
其他
getData(){db.collection("test").limit(3).skip(3).field({title:true,author:true}).orderBy("time","desc").get().then(res=>{this.setData({dataArr:res.data})})},filed 要查詢哪幾項
limit 只要幾條數據
skip 跳過幾條數據
orderBy 按要求排序
比較符
getData(){db.collection("test").where({hits:_.eq(999)//等于999 其他看api}).get().then(res=>{this.setData({dataList:res.data})})
},