排序在Mongoose和NodeJS中不起作用

xzv2uavs  于 2023-01-08  发布在  Node.js
关注(0)|答案(3)|浏览(171)
I am trying to sort my data by price, descending. In the following controller, I am able to filter for operations like greater than less than, less than or equal to... However, I create an if statement to check if a query has sort (localhost:3000/api/v1/tours?sort=price) and it does, so then in the block code, I am trying to sort. What ends up happening with the code below is the error

{
        "status": "failure",
        "results": "Parameter \"filter\" to find() must be an object, got price"
    }

我在上一门课,学生们用Mongoose 5,而我用6。每当我用其他代码,比如--if语句--

if (queryString.sort) {
      queryString = queryString.sort(req.query.sort);
    }

就会出现这样的错误

{
    "status": "failure",
    "results": "queryString.sort is not a function"
}

在我的 Postman 应用程序中。看起来我的if语句中的代码几乎被忽略或踩进了错误。

exports.getAllTours = async (req, res) => {
      try {
        let queryString = JSON.stringify(req.query);
        queryString = queryString.replace(
          /\b(gte|gt|lte|lt)\b/g,
          (match) => `$${match}`
        );
        let = queryString = JSON.parse(queryString);
    
        if (queryString.sort) {
          queryString = queryString.sort;
        }
        const tours = await Tour.find(queryString);
    
        res
          .status(200)
          .json({ status: 'ok', results: tours.length, data: { tours } });
        //TODO: Will fine tune error despite somewhat working
      } catch (err) {
        // eslint-disable-next-line no-console
        console.log(err);
        res.status(404).json({ status: 'failure', results: err.message });
      }
    };

以下是我的一些问题:
1.在这种情况下,如何正确地使用Mongoose的排序函数?

smdnsysy

smdnsysy1#

如果您想同时进行筛选和排序,则可以尝试

let queryString = req.query;
let API;

if(queryString.filter){
  API = Tour.find(queryString.filter);
}

if(queryString.sort){
  API = API.sort({[queryString.sort]: -1});
}

let tours = await API.exec();

res
  .status(200)
  .json({ status: 'ok', results: tours.length, data: { tours } });```
vjrehmav

vjrehmav2#

我意识到必须在find方法中使用JSON.parse。

exports.getAllTours = async (req, res) => {
      try {
        let queryString = JSON.stringify(req.query);
        queryString = queryString.replace(
          /\b(gte|gt|lte|lt)\b/g,
          (match) => `$${match}`
        );
    
        let query = Tour.find(JSON.parse(queryString));
    
        if (req.query.sort) {
          query = query.sort(req.query.sort);
        }
    
        const tours = await query;
        res
          .status(200)
          .json({ status: 'ok', results: tours.length, data: { tours } });
        //TODO: Will fine tune error despite somewhat working
      } catch (err) {
        // eslint-disable-next-line no-console
        console.log(err);
        res.status(404).json({ status: 'failure', results: err.message });
      }
    };
8ljdwjyq

8ljdwjyq3#

将查询代码放入if语句中以查找()所有数据,然后添加.sort()方法。
如果您想按价格排序,并且只显示符合条件的数据,您可以尝试以下操作:

let queryString = req.query;
let tours;

if (queryString.sort) {
  tours = await Tour.find({
    [queryString.sort]: {
      $gt: value,
      $lt: value
    }
  })
  .sort({
    [queryString.sort]: -1
  })
}

res
  .status(200)
  .json({ status: 'ok', results: tours.length, data: { tours } });

更多信息,您可以访问MongoDB .sort()

相关问题