Applet cloud batch delete data in the database

We developed a cloud cloud data inventory data, will inevitably encounter too much data, or some outdated data needs to be deleted. Prior to the development of cloud delete a section of the database can only be deleted. To batch delete a lot of trouble recently launched a cloud development method bulk delete data. Even slightly database a collection (table) in the deletion of all data transformation under implementation.

Old rules, look at the effect of FIG.

  • Such as deleting payroll in September 2019 salary

    can see that we successfully removed 7 data.

  • Delete all data on wages

    we can see our wages data table 768, all deleted.
    Next we will look at the specific implementation code

First, look at the official documentation on how to write


You can see by the chart, we can either delete a single, and can delete multiple.

We can see by the chart, where we can combine statements to achieve bulk delete.

Then look at the official demo given

a look we can know that it is written in a function in the cloud. So we Batch delete data in the database, must be achieved through the cloud batch function.
Address official document: https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-server-api/database/collection.remove.html

Second, we combine specific business to achieve bulk delete

1, first of all look at our wages table, there yuefen this field


For example, our November 2019 pay all of them filled in incorrectly, we want to batch delete all data yuefen to 2019.11, the corresponding code is shown below the red box code.

2, as a business code, we certainly want data QUICKER

Therefore, the definition of an input box for entering the month you want to delete. As shown below

3, delete all the data

同样的我们想删除所有数据,也比较依赖where。那门我们删除所有数据,该怎么匹配where语句呢。翻看官方文档,可以看到官方文档有判断某一个字段是否有值。所以我们编写的删除所有数据的代码如下。

这样我们就可以通过判断月份存在,就可以删除所有数据了,因为所有的数据都有月份的。

这样我们就可以实现小程序数据库里数据的批量删除操作了,官方其实也有为我们提供批量更新的操作,感兴趣的同学去官方文档看下就可以了。

https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-server-api/database/collection.update.html

完整的云函数源码直接给大家贴出来吧。

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
exports.main = async(event, context) => {
  let {
    type,
    yuefen
  } = event
  try {
    if (type == 'all') {
      const _ = db.command
      return await db.collection('gongzi').where({
        yuefen: _.exists(true) //只要月份字段存在,就删除
      }).remove()
    } else {
      return await db.collection('gongzi').where({
        yuefen: yuefen
      }).remove()
    }

  } catch (e) {
    console.error(e)
  }
}

后面我会写更多关于小程序,云开发,云数据库的文章,请持续关注。

Guess you like

Origin blog.51cto.com/14368928/2454054