unicloud6-count统计与add新增与批量添加

237 阅读2分钟

count 获取符合记录的数据条数

在云函数cloudDemo1中

  // 统计符合条件的记录条数
  let res = await db.collection("users").count();

在前端打印出来,值就是一个数字,符合查询条件的条数

image.png

新增记录

// 'use strict';
// 1.连接数据库,写在main函数外面里面都行
const db = uniCloud.database()
exports.main = async (event, context) => {
	// 2.获取users集合的引用(这个集合也就是这张表是自己创建的)
  // get方法是uni提供的用于获取这个表里的数据
  // await是等待异步请求
  // let res = await db.collection("users").get();
  // 统计符合条件的记录条数
  // let res = await db.collection("users").count();
  
  let res = await db.collection("users").add({
    name:"小红",
    gender:"女",
    address:"山东济南"
  })
  return res; 
};

现在数据库中有3条数据了,但是之前通过数据库插入的一条数据丢了,没有任何报错,应该是uniapp的问题

在云函数中插入的数据要在浏览器页面刷新一下,云数据库中才会有,不刷新就不存在,不知道为什么 image.png

上面是用对象的方法插入数据,还能通过数组包裹对象的方式进行批量插入

// 'use strict';
// 1.连接数据库,写在main函数外面里面都行
const db = uniCloud.database()
exports.main = async (event, context) => {
	// 2.获取users集合的引用(这个集合也就是这张表是自己创建的)
  // get方法是uni提供的用于获取这个表里的数据
  // await是等待异步请求
  // let res = await db.collection("users").get();
  // 统计符合条件的记录条数
  // let res = await db.collection("users").count();
  
  let res = await db.collection("users").add([
    {name:"科比"},
    {name:"麦迪"}
  ])
  return res; 
};

前端代码:

<template>

</template>

<script>
	export default {
		data() {
			return {
        listArr:[],
        userArr:[]
			}
		},
		onLoad() {
      // 连接云函数
      uniCloud.callFunction({
        name:"cloudDemo1",
        data:{}
      }).then(res=>{
        console.log(res);
      })
		},
	methods: {
		}
	}
</script>

<style lang="scss">

</style>

通过数组包裹对象的方式插入两条数据,刷新页面之后,返回了这两个对象的id image.png

再刷新云数据库,里面也有数据了

  • 云服务商为阿里云时,若集合不存在,调用add方法会自动创建集合。注意此方式创建的集合不带索引、表结构,尽量不要依赖此方式创建集合。