在客户端,用户可以通过一种形式来更新其个人资料,在该形式中,数据通过axios发送到nodejs express后端。我想用猫鼬来更新用户信息。这是我尝试过的:
userRouter.post('/update/:username', (req, res) => {
const update = {age: req.body.age, height: req.body.height, weight: req.body.weight, gender: req.body.gender}
const filter = {username: req.params.username}
User.findOneAndUpdate(filter, update, { new: true });
});
答案 0 :(得分:1)
findOneAndUpdate
上的 User
方法返回promise和接受回调的另一种方式。您没有通过任何导致此错误的操作。您可以尝试使用回调方法或下面编写的一种方法。
userRouter.post('/update/:username', async (req, res) => {
const update = {age: req.body.age, height: req.body.height, weight: req.body.weight, gender: req.body.gender}
const filter = {username: req.params.username}
const updatedDocument = await User.findOneAndUpdate(filter, update, { new: true });
return res.status(200).send(updatedDocument);
});
答案 1 :(得分:0)
在REST API规范中,更新服务器上的某些资源时,必须对请求使用PATCH
或PUT
方法。
您使用POST
方法。
在这里您可以这样做
首先,获取用户名并使用filter属性在数据库中搜索。
现在获取req.body
并应用更新的数据
app.patch('/update/:username', (req, res) => {
//You can pass req.body directly or you can separate object
const { age, height, weight, gender } = req.body;
const { username } = req.params;
const filter = { username : username }
const updatedUser = await User.findOneAndUpdate(filter, req.body, { new: true }).catch(error => {
return res.status(500).send(error);
});
return res.status(200).json({
message : "Updated user",
data: updatedUser
});
});