首页 > 解决方案 > MERN中的排序

问题描述

想法:我想在多种条件下对我的产品进行排序,例如按 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 排序而不是按价格排序。

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

标签: node.jsmongodb

解决方案


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

喜欢

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。


推荐阅读