我正在嘗試向端點“/api/user?username=idHere”設定補丁請求。它旨在采用 json 主體,并能夠讀取每個鍵值對并使用這些新值更新 MongoDB 中的用戶。但現在,“{$set: {key: req.body[key]}}”行是按字面意思解釋的,它試圖將實際單詞“key”設定為一個值,而不是請求正文中的鍵。我怎樣才能正確地實作這個目標?我當前嘗試此操作的代碼如下。
const updateUser = (req, res) => {
const db = mongoConnection.getDb();
const keys = Object.keys(req.body);
for (key in keys) {
db.collection('users').updateOne(
{username: req.query.username},
{$set: {key: req.body[key]}}
)
}
}
uj5u.com熱心網友回復:
JavaScript 允許您使用帶有方括號的引數化鍵名。
// Will use the value of the "key" variable for the key
{ [key]: req.body[key] }
// Will use the word "key" for the key
{ key: req.body[key] }
例如,
const req = { body: {
name: "CobaltGecko",
email: "[email protected]"
}};
const keys = Object.keys(req.body);
for(let key in keys) {
console.log({key: req.body[key]}); // logs {key: CobaltGecko}, {key: [email protected]}
}
for(let key in keys) {
console.log({[key]: req.body[key]}); // logs {name: CobaltGecko}, {email: [email protected]}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447598.html
標籤:javascript mongodb 表示
上一篇:引數未傳遞給服務器路由器
