mongodb 我无法在nodejs中获得电子商务网站API的排序结果

ippsafx7  于 2023-06-29  发布在  Go
关注(0)|答案(1)|浏览(106)

下面是根据用户传递查询参数对产品进行排序的逻辑

const getAllProduct = asynchandler( async ( req, res)=>{
    try {
        // filter the products search
        const queryObj ={...req.query};
        const excludefield = ["page","short","limit","fields"];// excluding uncessery field from query
        excludefield.forEach((el)=> delete queryObj[el]); 

        let queryString =JSON.stringify(queryObj) // convertig query in string      
        queryString = queryString.replace(/\b(gte|gt|lte|lt)\b/g, (match)=>`$${match}`) // this g will match all the else it will only match 1st
        // console.log(JSON.parse.queryString);
        
        let query = Product.find(JSON.parse(queryString)) // product filterin
       
        // shorting.........
        if (req.query.sort){  
            const sortBy = req.query.sort.split(",").join(" ");
            console.log(sortBy);
            query = query.sort(sortBy) 
        }else{
            query = query.sort('-createdAt')
           console.log("else sort by createdAt")
        }
        const product = await query;
        res.json(product)
    } catch (error) {
        throw new Error(error)
    }
})

但是我得到了空数组作为响应
下面是我的API请求:localhost:5000/API/product/?sort=类别,品牌
我正在寻找按类别分类的产品

hi3rlvi2

hi3rlvi21#

有很多问题,我不得不重写大部分。一些要点:
find()返回一个游标,你需要等待toArray();
要排序,你需要发送一个对象,1表示升序,-1表示降序,如下所示:{brand: 1}
筛选器中find()的参数不是排序,您将排序传递给查找
为了过滤,我在查询中添加了一个参数“filter”,如下所示:
http://localhost:5000/api/product/?sort=category,brand,limit&filter=name:red,size:big
您需要定义所有内容并一次性使用find().sor()
考虑此集合:

[

    {
        _id: ObjectId(),
        "category": 'Food',
        "brand": 'Two',
        "createdAt": ISODate(),
        "name": "Pink Grape",
        "size": "small"
    },
    {
        _id: ObjectId(),
        "category": 'Food',
        "brand": 'One',
        "createdAt": ISODate(),
        "name": "Red Apple",
        "size": "big"
    },
    {
        _id: ObjectId(),
        "category": 'Car',
        "brand": 'Zuui',
        "createdAt": ISODate(),
        "name": "Yellow Car",
        "size": "big"
    },
    {
        _id: ObjectId(),
        "category": 'Car',
        "brand": 'Aoim',
        "createdAt": ISODate(),
        "name": "Blue Car",
        "size": "medium"
    },
    {
        _id: ObjectId(),
        "category": 'Car',
        "brand": 'Two',
        "createdAt": ISODate(),
        "name": "Red Car",
        "size": "small"
    }

]

这条路:

app.get("/api/product/", async (req, res) => {
    try {
        const sortFields = req.query.sort?.split(',').filter(field => !["page", "short", "limit", "fields"].includes(field));
        let sortObj = {};
        sortFields?.forEach(field => sortObj[field] = 1);

        if (!req.query.sort) {
            sortObj = ({ createdAt: 1 });
        }

        const filters = req.query.filter?.split(',');
        let filterObj = {}
        filters?.forEach(filter => {
            const key = filter.split(":")[0];
            const value = filter.split(":")[1];
            filterObj[key] = { $regex: value, $options: 'i' }
        });

        const products = await Product.find(filterObj).sort(sortObj).toArray();
        res.json(products)
    } catch (error) {
        throw new Error(error)
    }
})

相关问题