簡體   English   中英

在貓鼬中將自定義字段設置為.find()的參數

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

我正在對我的api進行HTTP調用,以從mongodb中檢索文檔,並且在url中,我有兩個參數: campokeyphrase 我想看看所有這些都是參數坎普設置為我的關鍵詞的文檔。 例如:我的mongo中有一些類似的文檔:

classe: "4AT"
cognome: "XYZ"
email: "xyz.zyx@gmail.com"
idreg: "IUDQFEXFFR4DW133"
nome: "Francesco"
turni: ["g2t1", "g1t2", "g3t2"]
__v: 0
_id: "5c508d0b4810fc0ece8df2a9"

我將GET稱為“ localhost:3000 / nome / Francesco”,我想在“ nome”字段中選擇所有值為“ Francesco”的文檔。 但是問題是方法.find()接受如下參數:

.find({nome: keyphrase})

而不是像我想要的動態標題。 有機會嗎?

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

如果要基於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