如何使用Express中的比较运算符过滤查询字符串

时间:2016-06-08 18:13:24

标签: node.js mongodb express

如果我在数据库中有资源,我知道我可以在我的快递应用中使用mongodb npm包来过滤$gt$lt等内容以仅接收根据我想要的过滤器返回值。

我还知道如何将req.querymongodb结合使用,以便在我们的查询字符串与相等之后检索其结果(网址:{{ 1}},Express / mongodb:http://localhost:3000/fruit?type=apple)。

如何使查询字符串表明我只想要大于或小于某些值的值?如果我只是想"等于",我会将其作为另一个查询参数(collection.find(req.query)...)传递,但是如果我想要价格低于1的所有水果呢?

2 个答案:

答案 0 :(得分:1)

import asyncio
from pyppeteer import launch

async def intercept_response(res):
    resourceType = res.request.resourceType
    xhr_list = []
    if resourceType in ['xhr']:
        print(res.request.url)
        xhr_list.append(res.request.url)
    return xhr_list

async def main():
    browser = await launch(headless=False)
    page = await browser.newPage()
    page.on('response', intercept_response)
    await page.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1')
    await page.goto('https://www.iesdouyin.com/share/user/70015326114', waitUntil = 'networkidle2')
    await browser.close()

if __name__ == '__main__':
    url = asyncio.run(main())
    print(url)

//if need to find ratings greater then 3
//The query string may be:
//127.0.0.1:8000/api/v1/posts?ratings[gt]=3
//if we check the req.query
//{ ratings: { gt: '3' } }

答案 1 :(得分:0)

var filter = {};
if(req.query.type)
    filter.type = req.query.type;
if(req.query.price)
    filter.price = req.query.price;

// you cannot know if the incoming 
// price is for gt or lt, so

// add new query variable price_gt (price greater than)
if(req.query.price_gt) {
    filter.price = filter.price || {};
    filter.price.$gt = req.query.price_gt;
}

// add new query variable price_lt (price less than)
if(req.query.price_lt) {
    filter.price = filter.price || {};
    filter.price.$lt = req.query.price_lt;
}

collection.find(filter);