【问题标题】:Sort Mongodb data by price按价格对 Mongodb 数据进行排序
【发布时间】:2018-01-13 14:41:35
【问题描述】:

目标:我试图找到一种方法让用户在一个索引页面上按最高和最低价格对租金进行排序。

我的问题是我能弄清楚如何使它工作的唯一方法是为 lowprice 和 highprice 创建两个单独的页面。我只想有一个主索引。

下面显示的 pricelow 页面将数据从低到高过滤

        app.get("/pricelow", function(req, res){
        Listings.find({}).sort({price: 1}).exec(function(err, allListings){
               if(err){
                   console.log(err);
               } else {
               res.render("pricelow",{listings:allListings});
               }
          })
    });

//下面显示的pricehigh页面将数据从高到低过滤

app.get("/pricehigh", function(req, res){
    Listings.find({}).sort({price: -1}).exec(function(err, allListings){
               if(err){
                   console.log(err);
               } else {
               res.render("pricehigh",{listings:allListings});
               }
          })
    });

【问题讨论】:

    标签: node.js mongodb express search mongoose


    【解决方案1】:

    您可能已经注意到,两个代码之间的唯一区别是 sort() 条件。

    幸运的是,您可以在multiple ways 中进行排序。

    IMO 最简单的方法是传递一个字符串,例如price(升序)或-price(降序)通过查询参数。

    将两个路由处理程序合并为一个

    app.get('/rentals', function (req, res) {
        Listings.find({}).sort(req.query.sort).exec(function (err, listings) {
            if (err) {
                console.log(err);
            } else {
                res.render('rentals', { listings: listings });
            }
        })
    });
    

    排序时,请致电/rentals?sort=price/rentals?sort=-price。这种方法还允许您使用其他字段,例如/rentals?sort=anotherField.

    【讨论】:

    • 非常惊人的答案。非常感谢您的帮助。
    猜你喜欢
    • 2012-07-21
    • 2018-05-19
    • 1970-01-01
    • 2018-02-14
    • 2020-03-20
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多