zoukankan      html  css  js  c++  java
  • 云开发数据库的基本查询

    基础的部分,就是不涉及到小程序的聚合($)操作符(_)以及正则等一些高级操作的实现的查询(我是不是说了句废话。。。。)

    基础的内容其实看微信小程序官方文档就能看懂的,我就简单啰嗦一点我最初常用的一点方法(下面的索引可以自动跳转)

    五条内容,已经完成了一套基本的增删改查


    接下来的内容在Nodejs版本:10.15,云开发sdk版本:~2.1.2下使用


    先写一套基本的代码,接下来的所有代码都需要把这段内容加到中间
    
    const cloud = require('wx-server-sdk')
    cloud.init({
      env: cloud.DYNAMIC_CURRENT_ENV
    })
    const db = cloud.database();
    
    exports.main = async (event, context) => {
        // 内容区
    }
    

    getEntityById 根据id获取单条内容

    其实这个方法都可以不要的,直接用listEntityBy where id == 'xxxx'即可,区别在于这个返回的是对象,list方法返回的是数组。
    
    
    // 这是个解构函数,挺有趣的东西,可以去了解一下 传入对应的参数即可(集合名称、唯一标识(_id))
    const {collection, id} = event;
    
    return db.collection(collection)
    .doc(id)
    .get();
    

    listEntityBy 根据条件获取对象

    内容是改了微信小程序云开发提供的demo
    
     const {
        collection,
        data
      } = event;
    
      // 取出集合记录总数
      const countResult = await db.collection(collection).count()
      const total = countResult.total
    
      // 计算需分几次取
      const batchTimes = Math.ceil(total / 100)
      
      // 承载所有读操作的 promise 的数组
      const tasks = []
      for (let i = 0; i < batchTimes; i++) {
        const promise = db.collection(collection)
          .skip(i * MAX_LIMIT)
          .limit(MAX_LIMIT)
          .where(data)
          .orderBy('create_time', 'desc')  // 我一般会加上一个时间戳 表字段必增 倒序是为了查询内容后来居上(按理说还可以增加查询性能)
          .get()
        tasks.push(promise)
      }
    
      // 等待所有
      return (await Promise.all(tasks)).reduce((acc, cur) => {
        return {
          data: acc.data.concat(cur.data),
          errMsg: acc.errMsg,
        }
      })
    

    updateEntityBy 根据条件更新(单条更新传id即可)

    /**
     * 指定的数据更改
     * 
     * data: {
     *  where: {
     *      _id: 'xxxxxxx'
     *  },
     *  to: {
     *      name: 'Eve'
     *  }
     * }
     */
    const { collection, data } = event;
    
    return db.collection(collection)
        .where(data.where)
        .update({
            data: data.to
        })
    

    insertEntity 添加对象

    const {collection, data} = event;
    return db.collection(collection).add({data: data});
    

    removeEntity 删除对象

    // 这里的data指的是condition条件
    const { collection, data} = event;
    return await db.collection(collection)
        .where(data)
        .remove();
    

    目录跳转:微信小程序云开发数据库查询指南

  • 相关阅读:
    10. Regular Expression Matching
    9. Palindrome Number (考虑负数的情况)
    8. String to Integer (整数的溢出)
    7. Reverse Integer (整数的溢出)
    LeetCode Minimum Size Subarray Sum
    LeetCode Course Schedule II
    Linux 文件缓存 (一)
    LeetCode Tries Prefix Tree
    Linux : lsof 命令
    LeetCode Binary Tree Right Side View
  • 原文地址:https://www.cnblogs.com/Arunoido/p/13425309.html
Copyright © 2011-2022 走看看