云函数推荐结构
// 云函数入口文件const cloud = require('wx-server-sdk')cloud.init()const db = cloud.database();// 云函数入口函数exports.main = async (event, context) => { const wxContext = cloud.getWXContext() const _openid = wxContext.OPENID switch (event.fn) { case 'delete_file': return await cloud.deleteFile({ fileList: [event.url] }) case 'get_category': return get_category(event, _openid) case 'update_category': return update_category(event, _openid) case 'add_category': return add_category(event, _openid) case default: return }
普通分页查询
async function get_images(event, _openid) { let collection = 'images'; let page = event.page || 1; let limit = event.limit || 20; let where = event.where || {}; let skip = (page - 1) * limit let r_total = await db.collection(collection) .where(where) .count() let r_list = await db.collection(collection) .where(where) .skip(skip) .limit(limit) .field({ _id: true, srcset: true, title: true, artist_id: true }) .get() return { total: r_total.total, list: r_list.data }}
普通增删改
// 删除一条async function remove_images(event) { return await db.collection('images').doc(event._id).remove()}// 删除多条async function remove_muti_images(event) { let selected = event.selected; const _ = db.command return await db.collection('images') .where({ _id: _.in(selected) }) .remove()}// 新增一条async function add_images(event) { // 校验 return await db.collection('images').add({ data: event.record })}// 更新一条async function update_images(event) { let record = event.record let _id = record._id delete record._id // 校验 return await db.collection('images') .doc(_id) .update({ data: record })}
聚合分页查询
async function get_images(event, _openid) { let page = event.page || 1; let limit = event.limit || 20; let skip = (page - 1) * limit let where = event.where || {}; let r_total = await db.collection('images') .where(where) .count() let r_list = await db.collection('images') .aggregate() .lookup({ from: 'category', localField: 'category_id', foreignField: '_id', as: 'name' }) .match(where) .skip(skip) .limit(limit) .sort({ created_at: -1 }) .project({ _id: true, srcset: true, title: true, artist_id: true, name: '$name.name' }) .end() return { total: r_total.total, list:r_list.list }}
聚合group分类统计
async function get_category(event, _openid) { const $ = db.command.aggregate; let num = await db.collection('images').aggregate() .group({ _id: '$category_id', num: $.sum(1) }) .end() console.log(num.list) let r_list = await db.collection('category').get() let list = r_list.data.map(v => { let tmp = num.list.filter(n => n._id == v._id) if (tmp.length) { v.num = tmp[0].num } else { v.num = 0; } return v; }) return list;}