我的用戶物件結構如下:
{
"id": "",
"username": "",
"name": "",
"bio": "",
"email": "",
"profileImg": "",
"phoneNumber": 0,
"messagingPoints": 0,
"funds": 0,
"inventoryId": "",
"lastLogin": "2022-02-23T03:27:13.535Z",
"isPrivate": false,
"messagesReceived": []
}
我希望能夠訪問補丁端點來更新這些欄位中的任何一個。例如,/api/user?id=userId&name=John,應該能夠抓取欄位“name”并將其設定為 John。/api/user/id=?id=userId&[email protected] 應該抓取電子郵件欄位并將其設定為 [email protected]
我正在努力尋找 MongoDB 的檔案來實作這一點,所以我想知道這是否不可能?我是否需要為每個更新操作指定一個端點(例如:/api/user/name?id=userId&value=John 而不是 /api/user?id=userId&name=John)?
如果可能的話,我怎么能做到這一點?謝謝!
uj5u.com熱心網友回復:
您可以在更新過濾器中傳遞用戶 ID。您也可以在 PUT 請求的請求正文中傳遞資料,而不是查詢引數。
app.put('/api/user', async (req, res) => {
const { id, ...data } = req.body;
// Filter out any invalid fields
// Update documents where id field is equal to value of id in request body
await collection.updateOne(
{ id },
{ $set: data }
);
return res.json({ data: "User updated" })
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447601.html
標籤:javascript 节点.js mongodb 表示
上一篇:Node.jswebpack5錯誤,找不到模塊;重大變化:webpack<5用于包含node.js核心的polyfill
