小程序入门13:小程序云开发之数据库编辑记录

442 阅读2分钟

写在前面

本篇文章是微信小程序开发入门的第十三篇,介绍小程序云开发之数据库编辑记录

数据库:编辑记录

上一篇文章我们完成了编辑页面的开发,这篇文章我们实现编辑功能

首先,我们打开cloudfunctions\fruit\index.js文件,给云函数添加编辑记录的代码,添加的代码如下:

...
const edit = require('./edit/index');

// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.type) {
    ...
    case 'edit':
      return await edit.main(event, context);
  }
}

新建cloudfunctions\fruit\edit\index.js文件,编写数据库编辑记录的代码,小程序端将要修改的内容和记录id传过来,代码如下,同样,代码编写完成后需要上传并部署,或者开启本地调试,否则小程序端无法正常调用:

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

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();

// 修改数据库记录云函数入口函数
exports.main = async (event, context) => {
  try {
    await db.collection('fruit').where({
        _id: event.id
      })
      .update({
        data: {
          name: event.name,
          intro: event.intro,
          oriPrice: event.oriPrice,
          curPrice: event.curPrice,
          vipPrice: event.vipPrice,
          quantity: event.quantity,
          unit: event.unit,
        },
      });
    return {
      success: true,
      msg: '修改成功!'
    };
  } catch (e) {
    return {
      success: false,
      msg: '修改失败!'
    };
  }
};

接着在小程序端调用编辑数据库记录云函数,打开miniprogram\pages\fruit-edit\fruit-edit.js文件,添加如下代码,在编辑成功后页面跳转至详情页(使用wx.redirectTo跳转,表示关闭当前页面并跳转,点击上方返回时就不会返回到当前页面),编辑失败的话弹框提示失败信息:

...
  onEditSubmit() {
    wx.cloud.callFunction({
      name: 'fruit',
      data: {
        type: 'edit',
        ...this.data
      }
    }).then((res) => {
      console.log(res)
      const {
        success,
        msg
      } = res.result
      if (success) {
        wx.redirectTo({
          url: `/pages/fruit-detail/fruit-detail?id=${this.data.id}`,
        })
      } else {
        wx.showToast({
          title: msg,
          icon: 'error',
          duration: 2000
        })
      }
    }).catch((e) => {});
  }

保存以上代码后我们可以在页面上试一下,随便打开一条数据,修改内容如下,然后点击“确定编辑”按钮,就可以看到控制台返回的res的内容中显示“修改成功!”,同时页面也跳转至详情页,这里还有个问题,如果我们现在详情页点击返回,回到的列表页的数据并没有更新

image.png image.png

为了解决上述问题,我们打开miniprogram\pages\index\index.js文件,将onLoad改成onShow,不在页面onLoad的时候获取数据,在页面onShow的时候获取,此时我们再编辑一条数据,再从详情页返回,发现返回的还是详情页,这就涉及到小程序页面堆栈的知识,我将在下一篇文章详细说明

写在最后

以上就是小程序云开发之数据库编辑记录的全部内容