mongodb 在聚合响应中获取Promise

vsnjm48y  于 2023-11-17  发布在  Go
关注(0)|答案(1)|浏览(155)

我尝试使用aggreagte获取产品,后来我调用另一个API来获取产品及其计数,但我总是得到承诺内部响应。
怎么可以在exec()里面使用pagerc wait,我很困惑。
我目前使用的分页和获得产品的基础上限制,但需要总产品计数也。
下面是我对总价值的回应:
tottttt承诺{ 4 }

Product.aggregate([
      {
        
   $project: {
         
          document: "$$ROOT",

          floorAverage: {
            $floor: { $avg: "$ratings.star" }, //    //taking avg of rating arr for each prod
          },
        },
      },
      {
        $match: {
          $or: [
          
            obj1,
          ],
        },
      }, //now consider those prod which has avg rating
    ])
      .exec((err, aggregates) => {
        if (err) console.log("AGGREGATE ERROR", err);

        console.log("myagreg ids", aggregates);

       
          let starobj = {
            _id: aggregates,
          };
        
         //fetching products based on filter applied on these fetched avg rated products
          let newobj = {
            ...starobj,
            ...myfilterlist,
          };
       

          total = Product.find(newobj).countDocuments().exec();
        

          Product.find(newobj) 
            .populate("category", "_id name")
            .populate("subs", "_id name")
            .populate("postedBy", "_id name")
            .sort({ [sort]: order, _id: 1 }) 
            .skip((currentPage - 1) * perPage) 
            .limit(perPage)
            .exec((err, products) => {
              if (err) console.log("PRODUCT AGGREGATE ERROR", err);
              // res.json(products);
              console.log("totttttt", total);
              res.json({ products, total });

            });
        }

字符串
我尝试使用aggreagte获取产品,后来我调用另一个API来获取产品及其计数,但我总是得到承诺内部响应。
我目前使用的分页和获得产品的基础上限制,但需要总产品计数也。

1aaf6o9v

1aaf6o9v1#

你得到了一个promise,因为aggregate.exec();返回了一个promise,这是预期的行为。你需要await调用,然后你可以将解决的promise的结果存储在一个变量中。同样适用于你的Product.find
我不能评论你的聚合或数据库查询是否成功,但根据你分享的代码,如果你实现了这些更改,你应该能够达到预期的结果。注意,catch块可以捕获任何使用await的异步调用错误,但只能按顺序捕获。例如,如果aggregate抛出错误,它会直接跳转到catch,Product.find函数未执行:

try{
    let aggregates = await Product.aggregate([ 
        {
            $project: {
                document: "$$ROOT",
                floorAverage: {
                    $floor: { $avg: "$ratings.star" }, //    //taking avg of rating arr for each prod
                },
            },
        },
        {
            $match: {
                $or: [
                    obj1,
                ],
            },
        }, //now consider those prod which has avg rating
    ]);
    console.log('aggregates=', aggregates);

    let starobj = {
        _id: aggregates,
    };

    //fetching products based on filter applied on these fetched avg rated products
    let newobj = {
        ...starobj,
        ...myfilterlist,
    };

    const total = await Product.find(newobj).countDocuments();
    
    const products = await Product.find(newobj)
        .populate("category", "_id name")
        .populate("subs", "_id name")
        .populate("postedBy", "_id name")
        .sort({ [sort]: order, _id: 1 })
        .skip((currentPage - 1) * perPage)
        .limit(perPage);
    
    return res.json({ products, total });
    
}catch(err){
    console.log(err);
    return res.status(500).json({ message: 'Error on server' });
    //Handle err
}

字符串

相关问题