zoukankan      html  css  js  c++  java
  • 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: {}
        })
  • 相关阅读:
    vue脚手架引入MD5加密函数
    mysql 使用 MD5函数 校验账号密码
    iview引用自定义的图标
    vue 生命周期钩子
    mysql: show processlist 详解
    vue脚手架中动态引用图片的办法
    jsp 获取后端配置文件.properties的某个配置内容
    mybatis update 返回值
    python_判断缩写
    python_深拷贝与浅拷贝
  • 原文地址:https://www.cnblogs.com/helloyoyo/p/14985546.html
Copyright © 2011-2022 走看看