-1

I have a problem with doing Pagination. when including multiple & parameters. simply say, it doesn't work.

server.get("/search", async(req, res) => {
    try {
        const key = req.query.key;
        const value = req.query.value; 
        const text = req.query.text;

    let result = await collection.aggregate([                    
            {
                '$search': {
                    'text': {
                        'query': `${text}`,
                        'path': 'title'
                    }
                }
            },
            //match key here...
        ]).toArray();
        res.send(result)

    } catch (error) {
       console.error(error)
    }
})
Divyanshu Sah
  • 218
  • 4
  • 13
  • Looks like you are re-inventing a regular query string, i.e. `?key=value&key=value` - have a look, this functionality is built-in with express.js: https://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-express-js-on-node-js – Tomalak Jul 14 '21 at 11:14
  • ...uhm, yes? Express.js is Javascript. Node.js is Javascript. Please take a look at the linked question. – Tomalak Jul 14 '21 at 11:32

1 Answers1

1

The problem you have there is how you structured your endpoint url.

app.get("/search/:text/:key?&:value?&.....", (req,res)) => {....}

If you want to get the values you send via query string, you don't have to add the query params to the endpoint's url, you can simply have it like so:

app.get("/search", (req,res)) => {....}

And then build the request to the API like this:

http://localhost:4000/search?text=mango&brand=rasna

Like this you can access the properties of the request in the route's controller:

app.get("/search", (req,res)) => {
    const { text, brand } = req.query;
}

Optional values are fine, if you don't send them they will be undefined when you try to access their values in the controller so you can just check for them with conditionals.

app.get("/search", (req, res)) => {
    const { text, brand } = req.query;
     
    if(text) { ... }
    if(brand) { ... }
}

Obviously this is a very simple implementation just to explain the problem.

Rafael Freitas
  • 201
  • 2
  • 7
  • The second url didn't work because you have an extra question mark. Instead of: ```http://localhost:4000/search?text=Mango&key=Brand&value=Rasna?page=2``` It should be: ```http://localhost:4000/search?text=Mango&key=Brand&value=Rasna&page=2``` – Rafael Freitas Jul 14 '21 at 18:06
  • @DivyanshuSah pagination is a whole other topic. You should create a post for that or research stack overflow for pagination with MongoDB. I am sure there are many examples out there. Just for the note, the `page` parameter is not even being used in you code so there is no way for it to work. – Rafael Freitas Jul 17 '21 at 14:26