【问题标题】:sorting in MERNMERN中的排序
【发布时间】:2021-05-16 23:04:17
【问题描述】:

想法:我想在多种条件下对我的产品进行排序,例如按 createdAt 按 desc 或 asce 排序、按价格排序等。 问题:两者都工作正常,但是我如何根据用户的请求检查需要排序的内容,我们需要按 createdAt 或 price 对产品进行排序。

这是代码。

    const getProducts = async (req, res) => {
      try {

        const sortQuery = req.query.sort;
        console.log(sortQuery);

        const productMessages = await productMessage
          .find({})
          .sort({
            createdAt: sortQuery,
            price: sortQuery,
          })
          .populate("categoryId")
          .exec();
        // const productMessages = await productMessage.find();
        res.status(201).json(productMessages);
      } catch (error) {
        res.status(404).json({ message: error.message });
      }
    };

如果我发送查询以按价格对产品进行排序,它会给我结果,产品按 createdAt 排序而不是按价格排序。

Input: 1 //按价格排序产品 输出:按 createdAt 排序的产品 //但我需要价格

【问题讨论】:

  • 您应该只查询一次数据,然后将其呈现以使其按任意值排序。

标签: node.js mongodb


【解决方案1】:

您可以在执行前进行检查。

喜欢

const getProducts = async (req, res) => {
      try {
        const sortQuery = req.query.sort;
        console.log(sortQuery);
        
        let sortObject = {};
        if (req.query.sortField == "createdAt") {
           sortObject["createdAt"] = sortQuery
        } else if (req.query.sortField == "price") {
           sortObject["price"] = sortQuery
        }

        const productMessages = await productMessage
          .find({})
          .sort(sortObject)
          .populate("categoryId")
          .exec();
        // const productMessages = await productMessage.find();
        res.status(201).json(productMessages);
      } catch (error) {
        res.status(404).json({ message: error.message });
      }
    };

您必须在查询中传递 sortField。

【讨论】:

    猜你喜欢
    • 2021-10-18
    • 2017-11-07
    • 2022-08-07
    • 2021-08-30
    • 1970-01-01
    • 2021-05-04
    • 2022-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多