unicloud 數據庫基礎操作


一、clientDB操作數據庫

1、查找數據

//db.env.uid 當前用戶uid,依賴uni-id
//db.env.now 服務器時間戳
//db.env.clientIP 當前客戶端IP

// 查詢當前用戶的數據
const db = uniCloud.database()
let res = await db.collection('table')
.where({
  user_id: db.env.uid 
})
//如需一次查詢多條數據,可使用jql語法
.where(
    dbCmd.or({user_id:1},{user_id:2})
 )
.get()

//查詢列表分頁
const db = uniCloud.database()
db.collection('book')
  .where('status == "onsale"')
  .skip(20) // 跳過前20條
  .limit(20) // 獲取20條
  .get({
      getCount:true        //如需查詢數據總條數
    })
// 上述用法對應的分頁條件為:每頁20條取第2頁

//查詢並排序
const db = uniCloud.database()
  db.collection('order')
    .orderBy('quantity asc, create_date desc') // 按照quantity字段升序排序,quantity相同時按照create_date降序排序
    .get()

 

2、插入數據

const db = uniCloud.database();
db.collection("user")
    .add({name: '張三'})
    .then((res) => {
        uni.showToast({
            title: '新增成功'
        })
    })
    .catch((err) => {
        uni.showToast({
            title: '新增失敗'
        })
    })

3、刪除數據

//刪除單條記錄
const db = uniCloud.database();
db.collection("table1").doc("5f79fdb337d16d0001899566").remove()
//刪除該表所有數據
const db = uniCloud.database();
let collection = db.collection("table1")
let res = await collection.get()
res.data.map(async(document) => {
  return await collection.doc(document.id).remove();
});
//根據條件查詢刪除內容
const db = uniCloud.database();
db.collection("table1").where("a>2").remove().then((res) => {
        uni.showToast({
            title: '刪除成功'
        })
        console.log("刪除條數: ",res.deleted);
    })

4、更新數據

const db = uniCloud.database();
let collection = db.collection("table1")
let res = await collection.where({_id:'doc-id'})
  .update({
    name: "Hey",
  }).then((res) => {
        uni.showToast({
            title: '更新成功'
        })
    })

5、樹形結構菜單查詢(二級分類)

//DB Schema里配置parentKey來表達父子關系,然后查詢時聲明使用Tree查詢,就可以直接查出樹形數據
"properties": {
    "_id": {
      "description": "ID,系統自動生成"
    },
    "parent_id": {
      "bsonType": "string",
      "description": "父id",
      "parentKey": "_id", // 指定父子關系為:如果數據庫記錄A的_id和數據庫記錄B的parent_id相等,則A是B的父級。
    },
 }

//查詢
db.collection("department").get({
        getTree: {}
    })

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM