简体   繁体   English

在猫鼬中将自定义字段设置为.find()的参数

[英]Set a custom field as argument for .find() in mongoose

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 . 我正在对我的api进行HTTP调用,以从mongodb中检索文档,并且在url中,我有两个参数: campokeyphrase 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: 例如:我的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". 我将GET称为“ localhost:3000 / nome / Francesco”,我想在“ nome”字段中选择所有值为“ Francesco”的文档。 But the problem is that the method .find() accepts parameters like: 但是问题是方法.find()接受如下参数:

.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: PS:我的Express代码用于获取请求,如果有帮助的话:

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 如果要基于Campo和关键短语的值进行查询,请事先创建一个对象并将其用作查询

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);});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM