使用云开发进行增加和查询

微信小程序云开发

云开发优势

  • 无需搭建服务器
  • 免登录、免鉴权调用微信开放服务
  • 统一开发多端应用
  • 不限开发语言和框架

上手

创建一个集合

点击云开发打开云开发控制台点开数据库创建一个新的集合

在这里插入图片描述

在集合中点击插入字段插入数据

{
  // 描述,String 类型
  "description": "learn mini-program cloud service",
  // 截止时间,Date 类型
  "due": Date("2018-09-01"),
  // 标签,Array 类型
  "tags": [
    "tech",
    "mini-program",
    "cloud"
  ],
  // 个性化样式,Object 类型
  "style": {
    "color": "red"
  },
  // 是否已完成,Boolean 类型
  "done": false
}

在资源环境下创建一个Node.js云函数并在index.js中添加代码

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
// 自己的环境id
  env: 'tacp-2gbybh5e077c4887',
  traceUser: true
})
// 获取数据库的引用
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
// 获取一个集合的引用
  let res = await db.collection('todos').add({
    data: {
      description: "今天周一",
      due: new Date(),
      tags: [
        "cloud",
        "database"
      ],
      location: new db.Geo.Point(113, 23),
      done: false
    }
  })
  return res
}

云函数编写完成后点击右键进行上传并部署

在这里插入图片描述

如果修改完index.js中的代码还需上传可以在index.js上右键点击云函数增量上传:更新文件

在这里插入图片描述

在pages中新建页面text并添加按钮

<button type="submit" bindtap="cloud_add">云函数添加</button>

在text.js中编写代码

async cloud_add(){
    let res=await wx.cloud.callFunction({
    // 云函数的名字
      name:'add'
    })
    console.log(res);
 },

点击按钮后查看云开发控制台中的数据库

在这里插入图片描述

对数据进行单条查询

创建一个新的node.js云函数并在index.js中编写如下代码

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'tacp-2gbybh5e077c4887',
  traceUser: true
})
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  let res=await db.collection('todos').doc('17453ede60865ee5045ac9363ec46efc').get()
  return res
}

在text页面添加一个新的按钮

<button type="submit" bindtap="get_odd">获取单条数据</button>

在text.js中编写代码

async get_odd(){
    let res=await wx.cloud.callFunction({
      name:'get_odd'
    })
    console.log(res);
  },

点击按钮后查看控制台console的输出

在这里插入图片描述

对数据进行多条查询

创建一个新的node.js云函数并在index.js中编写如下代码

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'tacp-2gbybh5e077c4887',
  traceUser: true
})
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  let res=await db.collection('todos').where({
    description:event.description
  }).get()
  return res
}

在text页面添加一个新的按钮

<button type="submit" bindtap="get_odds">获取多条数据</button>

在text.js中编写代码

 async get_odds(){
    let res=await wx.cloud.callFunction({
      name:'get_odds',
      description:'今天周一'
    })
    console.log(res);
  },

点击按钮后查看控制台console的输出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值