2021-02-08

微信小程序-云函数实现用户信息添加云数据库

一、效果

在这里插入图片描述

二、实现

1.login云函数实现

const cloud = require('wx-server-sdk');

// 先初始化 cloud,后调用API
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  //两个环境时需要设置具体环境
  env: 'test-*********',
})
const db = cloud.database();

exports.main = async (event, context) => {
  console.log(event)
  console.log(context)
  const wxContext = cloud.getWXContext()

  //定义一个对象存储用户信息
  const {
    nickName,
    avatarUrl,
    gender,
    city,
    province
  } = event;
  
  //当前return返回给小程序,根据结果判断,再去给小程序返回信息
  //统计user中该openid存在的数量
  return db.collection('user').where({
    _openid:wxContext.OPENID
  }).count()
  
  .then(res => {
    if(res.total > 0){
      return {
        code:200,
        errMsg:'用户已经存在'
      }
    }
    else{
      return  db.collection('user').add({
        data:{
          _openid:wxContext.OPENID,
          nickName:nickName,
          avatarUrl:avatarUrl,
          gender:gender,
          city:city,
          province:province,
          time:new Date()
        }
      })
    }
  })
  
  // return {
  //   event,
  //   openid: wxContext.OPENID,
  //   appid: wxContext.APPID,
  //   unionid: wxContext.UNIONID,
  //   env: wxContext.ENV,
  // }
}


2.调用云函数

// pages/login/login.js
var that;
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo:null,
  },
  bindGetUserInfo(e){
    //this:这个页面整个对象
    console.log(e);
    if(e.detail.userInfo){
      //存储到本地
      wx.setStorage({
        //序列化
        data: JSON.stringify(e.detail.userInfo),
        key: 'userInfo',
        success(res){
          console.log("setStorage success:",res);
          that.addUser(e.detail.userInfo);
          wx.redirectTo({
            url: '../index/index',
          })
        }
      }) 
    }
    else{

    }
  },
  //添加用户信息到云数据库
  addUser(userInfo){
   wx.cloud.callFunction({
     name:'login',
     data:userInfo
   }).then(res=>{
      console.log("callFunc success",res);
   }).catch(err=>{
      console.error("callFunc fail",err);
   })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   that = this;
    //从本地获取信息存储到页面userInfo
    // wx.getStorage({
    //   key: 'userInfo',
    //   success(res){
    //     //转换成对象
    //     console.log("getStorage success:",JSON.parse(res.data));
    //     that.setData({
    //       userInfo:JSON.parse(res.data)
    //     })
    //   }
    // })
   
  },
})

三、记录

使用云函数本地调试,先init再调用其他的api,本地文件中如果只有一个云函数可能会报错
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值