When making an HTTP call to my api to fetch documents from a mongodb, I include two parameters in the URL: campo and keyphrase. My goal is to retrieve all documents where the parameter campo is set to my specified keyphrase. For example, if I have some documents like this stored in MongoDB:
classe: "4AT"
cognome: "XYZ"
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef979695c1959697af88828e8683c18c8082">[email protected]</a>"
idreg: "IUDQFEXFFR4DW133"
nome: "Francesco"
turni: ["g2t1", "g1t2", "g3t2"]
__v: 0
_id: "5c508d0b4810fc0ece8df2a9"
If I make a GET request to "localhost:3000/nome/Francesco", I want to retrieve all documents with the value "Francesco" in the "nome" field. However, the issue lies in the fact that the .find() method only accepts parameters in the format:
.find({nome: keyphrase})
and not as dynamic headers as I would prefer. Is there a way to achieve this?
PS: Below is my Express code for handling the GET request:
app.get("/api/ragazzi/:campo/:keyphrase",(req, res, next) => {
let campo = req.params.campo.toLowerCase();
let keyphrase = req.params.keyphrase;
Ragazzo.find({campo : keyphrase})
.then(documents =>{
res.status(200).json({
codice: "ok",
risultato: documents
});
})
.catch((err)=>{console.log(err);});
});