各中订单状态一次性从数据库返回有没有更好的方法?
发布于 3 年前 作者 weisun 5065 次浏览 来自 分享

小程序云开发,查询数据库中的各种订单状态的记录个数汇总时,如何一次性从数据库返回所有订单状态的记录个数?

比如我在云数据库中新建了一个数据集合 order, 存储有若干订单, 订单状态字段为_orderStatus( 待分配订单:0表示、进行中订单:1表示、已完成订单:2表示、已取消订单:-1表示),如何一次性从数据库返回所有订单状态的记录个数。我用的是如下方法,虽然能成功返回数据,但是个人感觉因该有更好的实现方法。

const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command;

//查询符合条件的订单记录个数
exports.main = async (event, context) => {
    console.log("正在调用云函数:[返回符合日期条件的各种订单状态汇总] [getRecordsCount]:", event)
    let orderCancel, orderWaiting, orderProgress, orderCompletion
    try {
        //取消订单
        orderCancel = await db.collection('order')
            .where({
                _orderStatus-1,
                _orderGenerationTime: _.gte(event.sdate).and(_.lte(event.edate))
            }).count({
                successres => {
                    return res.result.total
                }
            });
        //等待分配订单
        orderWaiting = await db.collection('order')
            .where({
                _orderStatus0,
                _orderGenerationTime: _.gte(event.sdate).and(_.lte(event.edate))
            }).count({
                successfunction (res{
                    return res.result.total
                }
            });
        //进行中订单
        orderProgress = await db.collection('order')
            .where({
                _orderStatus1,
                _orderGenerationTime: _.gte(event.sdate).and(_.lte(event.edate))
            }).count({
                successfunction (res{
                    return res.result.total
                }
            });
        //已完成订单
        orderCompletion = await db.collection('order')
            .where({
                _orderStatus2,
                _orderGenerationTime: _.gte(event.sdate).and(_.lte(event.edate))
            }).count({
                successfunction (res{
                    return res.result.total
                }
            });
    } catch (err) {
        console.error(err);
    }
    return {
        orderCancel: orderCancel,
        orderWaiting: orderWaiting,
        orderProgress: orderProgress,
        orderCompletion: orderCompletion
    }
}

执行结果如下:

2 回复

感谢@Mr.Zhao ,修改后代码如下

const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command;
const $ = db.command.aggregate

//查询符合条件的订单记录个数
exports.main = async (event, context) => {
    console.log("正在调用云函数:[返回符合日期条件的各种订单状态汇总] [getRecordsCount]:", event)
    try {
        return await db.collection('order').aggregate()
        .match({
            _orderGenerationTime: _.gte(event.sdate).and(_.lte(event.edate))
          })
            .group({
                _id'$_orderStatus',
                num: $.sum(1)
            })
            .end()
    } catch (err) {
        console.error(err);
    }
}

你为什么不用group?

回到顶部