PouchDB分组与汇总:实现销售数据求和转换
解决PouchDB文档中salesx数组求和需求
我来帮你搞定这个需求!核心思路很简单:先从PouchDB取出目标文档,对salesx数组里的qty值做累加求和,把原数组替换成计算结果,salesy保持原有结构不动就好。
针对单分类的基础实现
先看适配你示例文档的版本:
// 假设你的PouchDB实例已经初始化完成,命名为db db.get('1') .then(doc => { // 定位到category1下的salesx数组 const salesxList = doc.categories.category1.salesx; // 计算qty总和:注意qty是字符串类型,必须转成数字再累加,避免字符串拼接 const salesxTotal = salesxList.reduce((total, item) => { return total + parseInt(item.qty, 10); }, 0); // 替换原salesx数组为求和结果 doc.categories.category1.salesx = salesxTotal; // 如果需要把处理后的文档更新回数据库,就调用put方法;不需要的话直接跳过这步 return db.put(doc); }) .then(updatedInfo => { console.log('处理完成,更新后的文档:', updatedInfo); }) .catch(error => { console.error('处理过程出错:', error); });
扩展:多分类场景的通用处理
如果你的文档里有多个分类(比如category2、category3),可以用遍历方式批量处理:
db.get('1') .then(doc => { // 遍历所有分类节点 Object.keys(doc.categories).forEach(categoryKey => { const currentCategory = doc.categories[categoryKey]; // 只对存在salesx的分类做处理 if (currentCategory.salesx) { currentCategory.salesx = currentCategory.salesx.reduce((total, item) => { return total + parseInt(item.qty, 10); }, 0); } }); return db.put(doc); }) .then(updatedInfo => { console.log('批量处理完成:', updatedInfo); }) .catch(error => { console.error('批量处理出错:', error); });
关键注意点
- 必须把
qty转成数字类型(用parseInt或Number()都可以),不然会出现字符串拼接的错误(比如"2"+"3"得到"23"而非5) - 如果你只是需要处理后的对象、不需要更新回数据库,直接去掉
db.put(doc)步骤,处理完文档后直接使用即可
内容的提问来源于stack exchange,提问作者A. Blom
相关产品推荐
相关产品推荐

