[英]mongoose how to update an user profile with id
我在 nodejs 和 mongoose 中創建了一個簡單的 CRUD 操作。使用 RESTAPI 更新用戶。 Insomnia 中的錯誤消息
Error: Server returned nothing (no headers, no data)
URL
http://localhost:1337/api/users/update/63ab9b716065482273e58b75
@PUT方法
router.put("/update/:id",updateUser)
const updateUser = async (req,res,next) => {
if (req.params.id === req.user.id) {
try {
const updateuser = await User.findByIdAndUpdate(req.params.id, {
$set:req.body,
})
res.status(200).json(updateuser)
} catch (error) {
next(error)
}
}
}
如何更新用戶ID
req.params.id
將是字符串類型,而req.user.id
可能是 ObjectId 類型。
你能試試這個嗎:
if (req.params.id.toString() === req.user.id.toString()) {
前面提到req.user.id類型是ObjectId。 當 id 不相同時,您也應該發送錯誤。
您的代碼示例:
const updateUser = async (req, res, next) => {
try {
if (req.params.id !== req.user.id.toString()) {
// Send error in here.
}
const updateuser = await User.findByIdAndUpdate(req.params.id, {
$set: req.body,
});
res.status(200).json(updateuser);
} catch (error) {
next(error);
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.