Экспресс JS с неограниченным параметром запроса?

Я пытаюсь установить неограниченный параметр запроса в express js, но не мог понять, как мне реализовать это в моем коде. я использую MongoDB aggeration

Я хочу создавать неограниченное количество граней, поиск которых выполняется в несколько этапов


Что работает так :

      'http://localhost:4000/search?text=mango'
'http://localhost:4000/search?text=mango&key=brand&value=rasna' //unlimited facets.
'http://localhost:4000/search?text=mango&key=brand&value=rasna&key=color&value=yellow'  //unlimited facet parameters

Вот мой код для этого:

      app.get("/search", async(request, response) => {
    try {
        const textsearch = request.query.text;

        var keystore = request.query.key;      //storing `key` in 'keystore'
        var valuestore = request.query.value;  //storing `value` in `valuestore`

        if (keystore, valuestore) {

            facetjson = [
             {
                '$match': {
                    [keystore]: `${valuestore}`  //Storing key and value in $match
                }
             }
           ]

            const Pipeline = [{
                    '$search': {
                        'text': {
                            'query': `${textsearch}`,
                            'path': 'title',
                        }
                    }
                },
                {
                    '$limit': 5
                }
            ]

            //Pushing 'facetjson' array into Pipeline array to make a filtered search possible.

            const newitem = insert(Pipeline, Pipeline.length - 1, facetjson) 

            let result = collection.aggregate(newitem).toArray();
            response.send(result);
        } else {
            const Pipeline = [{
                    '$search': {
                        'text': {
                            'query': `${textsearch}`,
                            'path': 'title',
                        }
                    }
                },
                {
                    '$limit': 5
                }
            ]
            let result = collection.aggregate(Pipeline).toArray();
            response.send(result);
        };
    } catch (error) {
        response.status(500).send({ message: error.message });
    }
})

(Пример кода JSFIDDLE)[https://jsfiddle.net/divyanshuking/z0vo589e/]

==> Я знаю, что мне нужно пройти $match в Pipeline массив каждый раз для одного Key , ValueПара. Выполняя много поисков в Google, я понял, что нужно использовать Rest Parameter (...keystore,...valuestore). Но я не знал, как это реализовать. У вас есть идеи, как лучше решить эту проблему? Пожалуйста, помогите мне:

2 ответа

Решение

URL-адрес вашего запроса имеет неправильную структуру для параметров запроса. Если вы хотите передать несколько пар kay / value в URL-адресе, правильная структура будет такой:

  • 'http: // localhost:4000 / search?text=mango&brand=rasana&color=yellow

Этот код должен работать с такой структурой URL:

      app.get("/search", async(request, response) => {
    try {
        //We need "search pipeline stage" in all conditions. whether we got a key/value pair in query or not. 
        //so we use "search stage" when declare pipeline array;
        let pipeline = [{
            '$search': {
                'text': {
                    'query': `${request.query.text}`,
                    'path': 'title',
                }
            }
        }];
        //If there are keys/values pairs in the query parameters, we add match stage to our pipeline array;
        if(request.query) {
            let match = {};
            for(let item in request.query){
                match[item] = request.query[item];
            }
            pipeline.push({'$match': match})
        }
        //Finally, we add our "limit stage" to the pipeline array;
        pipeline.push({'$limit' : 5});
        let result = collection.aggregate(pipeline).toArray();
        response.status(200).send(result);
    } catch (error) {
        response.status(500).send({ message: error.message });
    }

})

Почему бы вам не использовать forEach или что-то в этом роде

      function endPoint (req, res) {
const queriesFound ={}

req.query.forEach(query=>{

queriesFound[query]=query;
}

QueriesFound will be an object

{ “Name”:”Name”, “AnotherParam”:”AnotherParam” }

}

// QueriesFound будет объектом

{"Name": "Name", "AnotherParam": "AnotherParam"}

Другие вопросы по тегам