【问题标题】:Add number of products for category [duplicate]为类别添加产品数量[重复]
【发布时间】:2019-10-21 13:14:32
【问题描述】:

我想在类别中添加字段,其中包含与该类别相关的产品数量 我的代码是

exports.paginate = async (Model,page,limit,sort,populate) => {
     const Product = require('../models/product')
     const count = await Model.countDocuments()
     const pages = Math.ceil(count/limit)
     const skip = (page - 1) * limit
     let data = await Model
     .find()
     .populate(populate)

     .limit(parseInt(limit))
     .skip(parseInt(skip))
     .sort(sort)
     let data2 = data.map(  (item) => {
          item.set('productCount', Product.find().countDocuments(),{strict:false});
          return item

     })
     return {
          data2,
          pages,
          totalItems:count,
          lastPage:pages,
          nextPage:parseInt(page)+1
     }
}

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    经过多次尝试,我找到了解决方案

    let data2 = await Promise.all( data.map( async (item) => {
              item.set('productCount', await Product.find({categories:item._id}).countDocuments()  ,{strict:false});
              return item
    
         }))
    

    【讨论】:

      猜你喜欢
      • 2018-06-07
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      相关资源
      最近更新 更多