使用聚合基于字符串数组过滤元素

时间:2019-07-15 11:23:46

标签: node.js mongoose aggregation

我正在尝试为我的网上商店项目实施搜索,并且在基于搜索查询进行过滤时遇到了麻烦,我设法通过过滤器解决了该部分,但是在遍历搜索参数数组时遇到了麻烦。 例如,我想基于搜索字符串“ samsung galaxy a6”进行搜索 我想获取文档数组并首先通过三星过滤它们,然后按星系然后再按a6过滤其余文档,我也想对文档名称进行部分匹配,对其他属性进行完全匹配。

这是我尝试的代码,它没有完成,但是我认为它显示了我想要实现的逻辑,我设法在for循环内完成它,但是我想做的是在数据库内部完成

我查看了此文档,但对我没有帮助,在此先感谢https://docs.mongodb.com/manual/reference/operator/aggregation/filter/

    let query = {};
    let searchArray
    if (producer)
        query.producer = producer.split(delimiterFilters) //filter
    if (ramMemory)
        query.ramMemory = ramMemory.split(delimiterFilters) //filter
    if (processor)
        query.processor = processor.split(delimiterFilters) // filter
    if (graphicCard)
        query.graphicCard = graphicCard.split(delimiterFilters) // filter
    if (search) {
        searchArray = search.toLowerCase().split(delimiterSearchQuery) //array of search parameters
        console.log(searchArray)


    }

    let products
    try {
        //products = await Phone.find(query)
        products = await Phone.aggregate([{ $match: query }]) //filtering products by filters,this is where i want to do filter by search parameters

    } catch (e) {
        res.status(500).send()
    }

    console.log(products.length);
    if (searchArray) {
        for (searchParam of searchArray) {
            for (product of products) {

                if (searchParam === product.screenSize.toString().toLowerCase()) {

                    continue
                }
                if (searchParam === product.producer.toLowerCase()) {

                    continue
                }
                for (let i = 0; i < products.length; i++) {
                    if (products[i] === product) {
                        console.log('izbacio bratica')
                        products.splice(i, 1)
                        i--;
                    }
                }
            }
        }

    }


0 个答案:

没有答案