i'm doing an HTTP call to my api to retrieve documents from a mongodb and in the url i have two parameters: campo and keyphrase . I wanna look for all the documents which have the parameter campo set to my keyphrase . Eg: I have a few docs like this in my mongo:
classe: "4AT"
cognome: "XYZ"
email: "xyz.zyx@gmail.com"
idreg: "IUDQFEXFFR4DW133"
nome: "Francesco"
turni: ["g2t1", "g1t2", "g3t2"]
__v: 0
_id: "5c508d0b4810fc0ece8df2a9"
I call GET to "localhost:3000/nome/Francesco" and i wanna pick all the documents with value "Francesco" in field "nome". But the problem is that the method .find() accepts parameters like:
.find({nome: keyphrase})
and not dynamical headers like i want. Is there any chance to do it?
PS: my Express code for get request, if it helps:
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);});
});
尝试
.find({ [campo] : keyphrase})
If you want to query based on the value of campo and keyphrase then create an object in beforehand and use it as the query
app.get("/api/ragazzi/:campo/:keyphrase",(req, res, next) => {
let campo = req.params.campo.toLowerCase();
let keyphrase = req.params.keyphrase;
let query = {};
query[campo] = keyphrase
Ragazzo.find(query)
.then(documents =>{
res.status(200).json({
codice: "ok",
risultato: documents
});
})
.catch((err)=>{console.log(err);});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.