簡體   English   中英

如何在我的 React 應用程序中從 mongodb 數據庫中獲取對象的 ID?

[英]How do I get the ID of an object from mongodb database in my react application?

我在建築中學習。 我正在使用 Reactjs、Nodejs、Mongodb 構建博客管理系統。 我想在數據庫中存儲一些前端值,以便我授予管理員權限的任何人都可以發布、編輯和刪除這些值。 這些值是網站名稱、子名稱、側邊欄生物描述、標題圖像和生物圖像。

這是創建值的代碼:

//create new frontend paramters into database
router.post("/", async (req, res) =>{
const newFrontendValues = new Frontend(req.body);//we called the    frontend model we created and we used req.body

try{
    const savedFrontendValues = await newFrontendValues.save()//we tried to save the frontend values created
  
    
    res.status(200).json(savedFrontendValues)
}catch(err){
   res.status(500).json(err)
}

}); 

我在 node 中編寫了代碼以在創建它們后獲取這樣的值:

//get frontend parameters
router.get("/:id", async (req, res) =>{
try{
    const frontend = await Frontend.findById(req.params.id)
    res.status(200).json(frontend)
}catch(err){
    res.status(500).json(err)
}
})

我的服務器api代碼

app.use("/api/frontend", frontend)

作為反應,我想調用值的 _id 但我迷路了。 我真的不知道該怎么做。 它在郵遞員中工作正常,因為我可以直接實現值 _id。 見附件圖片在此處輸入圖片說明

但是在 React 中,我希望它是動態的。

這是我的反應代碼:

 useEffect(() => {
  const fetchFrontendValue = async () =>{
      const res = await axios.get("/frontend")
      console.log(res.data)
  }
 fetchFrontendValue()
 }, [])

我如何將 _id 添加到這個

axios.get("/frontend")

您想查看獲取請求參數。 通常作為慣例,人們在 URL 中傳遞它們。 所以它會類似於http://localhost:5000/api/frontend?id=617944dc7e00022337a483be78並且在 API 端,您將使用req.body.id將其傳遞給數據庫。 還有其他方法可以做到這一點,但這是最常見的,因為一些舊瀏覽器會刪除附加到 GET 請求的參數。 這是一個鏈接: https : //www.w3schools.com/tags/ref_httpmethods.asp

您應該考慮尋求完整的解決方案。 在基本層面上,您應該遵循以下步驟

  1. 實現一個后端路由/getall以這種方式提取數據庫中的所有項目

    await Frontend.find({})

  2. 在前端呈現獲取的列表,使每個項目都是 React UI 項目,並且作為每個項目的一部分,您有用於刪除和更新項目數據的按鈕

    {backendData?.map((item, index)=><SingleItem key={item?._id} data={item} />)}

  3. 由於每個 SingleItem 都有更新和刪除按鈕以及 mongodb ID 作為數據的一部分,因此單擊更新和刪除按鈕,您將從數據中獲取 id 並在后端調用相關的 DB Url

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM