unicloud5-获取集合collection并get请求数据库

107 阅读1分钟

云函数通过传统方式操作数据库

文档地址:uniapp--unicloud--云函数通过传统方式操作数据库 uniapp.dcloud.net.cn/uniCloud/cf… 这是mongoDB的本身写法,小程序提供了一些其他写法,尤其是例如聚合操作(例如计算最大值、最小值、平均值等),原生写法较麻烦,uniapp提供的方法简单些

新建一个云函数测试

还是右键cloudfunction创建一个云函数cloudDemo1,然后还是默认模板,创建

云函数代码: index.js

// '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();
  return res; 
};

前端代码: index.vue

<template>
	<view class="home">
    <view class="row" v-for="item in listArr" :key="item.id">
      <image :src="item.picurl" mode=""></image>
      <view class="">{{item.title}}</view>
    </view>
	</view>
</template>

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

<style lang="scss">
.row {
  border-bottom: 1px solid #ccc;
  padding: 30rpx;
}
</style>

页面中获取到的返回值: image.png

渲染内容到页面

<template>
	<view class="home">
    <view v-for="item in userArr" :key="item._id">
      <view class="">姓名:{{item.name}}</view>
      <view class="">性别:{{item.gender}}</view>
      <view class="">电话:{{item.tel}}</view>
      <view class="">email:{{item.mail}}</view>
    </view>
	</view>
</template>

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

<style lang="scss">
.row {
  border-bottom: 1px solid #ccc;
  padding: 30rpx;
}
</style>

image.png