腾讯云函数 史上最复杂的聚合查询

需要对前端 传过来的多个查询条件 在云函数里进行处理拼装,并连接多个表查询。

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate
const objFilter2Array = (obj, property) => {
  const asArray = Object.entries(obj);
  const filtered = asArray.filter(([key, value]) => key !== property);
  const result = filtered.map(item => {
    let obj = {}
    obj[item[0]] = item[1]
    return obj
    // return Object.fromEntries([item])  cloud function can not use it
  })

  return result
}

exports.main = async (event, context) => {

  const { num, limit = 300, from, to1, to2, to3,
    f_field1, t_field1,
    f_field2, t_field2,
    f_field3, t_field3,
    condition = {}, sorter = { createTime: -1 } } = event
  if (condition.hasOwnProperty('detection_plan')) {
    const value = condition['detection_plan']
    switch (value) {
      case 'all':
        delete condition.detection_plan
        break;
      case 'other':
        condition['detection_plan'] = _.not(_.elemMatch(_.in(['TA001-无创产前基因检测',
          'TW023-无创产前基因检测plus1.0',
          'TA002-NGS染色体异常检测',
          'TA008-52种新生儿遗传代谢病筛查'])))
        break;
      default:
        break;
    }
  }
  // num 关联的表的个数
  try {
    let res
    if (num == 1) {
      res = await db.collection(from).aggregate()

        .lookup({
          from: to1,
          localField: f_field1,
          foreignField: t_field1,
          as: "to1List"
        })
        .match(condition)
        .sort(sorter)
        .limit(limit)
        .end()
    }
    else if (num == 2) {
      if (condition.hasOwnProperty('createTime') && condition['createTime'].length === 2) {
        const value = condition['createTime']
        const start = new Date(value[0]).toJSON()
        const end = new Date(value[1]).toJSON()
        let matched = objFilter2Array(condition, 'createTime')
        res = await db.collection(from).aggregate()
          .lookup({
            from: to1,
            localField: f_field1,
            foreignField: t_field1,
            as: "to1List"
          })
          .lookup({
            from: to2,
            localField: f_field2,
            foreignField: t_field2,
            as: "to2List"
          })
          .match(
            _.and([...matched,
              _.expr(
                /**
                 * 时间范围查询
                 */
                $.and([
                  $.gte([
                    '$createTime',
                    $.dateFromString({
                      dateString: start,
                    }),
                  ]),
                  $.lte([
                    '$createTime',
                    $.dateFromString({
                      dateString: end,
                    }),
                  ]),
                ])
              )
            ]
            )
          )
          .sort(sorter)
          .limit(limit)
          .end();

      } else {
        res = await db.collection(from).aggregate()
          .lookup({
            from: to1,
            localField: f_field1,
            foreignField: t_field1,
            as: "to1List"
          })
          .lookup({
            from: to2,
            localField: f_field2,
            foreignField: t_field2,
            as: "to2List"
          })
          .match(condition)
          .sort(sorter)
          .limit(limit)
          .end()
      }
    }
    else {
      res = await db.collection(from).aggregate()
        .lookup({
          from: to1,
          localField: f_field1,
          foreignField: t_field1,
          as: "to1List"
        })
        .lookup({
          from: to2,
          localField: f_field2,
          foreignField: t_field2,
          as: "to2List"
        })
        .lookup({
          from: to3,
          localField: f_field3,
          foreignField: t_field3,
          as: "to3List"
        })
        .match(condition)
        .sort(sorter)
        .limit(limit)
        .end()
    }
    return { msg: true, res }
  }
  catch (e) {
    return { msg: false, res: e }
  }
}
设置