Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用mongoose更新用户配置文件信息_Javascript_Node.js_Express_Mongoose - Fatal编程技术网

Javascript 如何使用mongoose更新用户配置文件信息

Javascript 如何使用mongoose更新用户配置文件信息,javascript,node.js,express,mongoose,Javascript,Node.js,Express,Mongoose,在客户端,用户可以通过表单更新其配置文件,其中数据通过axios发送到nodejs express后端。我想使用mongoose更新用户信息。以下是我尝试过的: userRouter.post('/update/:username', (req, res) => { const update = {age: req.body.age, height: req.body.height, weight: req.body.weight, gender: req.body.gender}

在客户端,用户可以通过表单更新其配置文件,其中数据通过axios发送到nodejs express后端。我想使用mongoose更新用户信息。以下是我尝试过的:

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 });
});


在REST API规范中,当更新服务器上的某些资源时,您必须使用
补丁
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
  });
});

User
上的
findOneAndUpdate
方法返回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);
  });

有什么问题吗?数据库中没有任何内容正在更新,控制台显示POST请求失败。请尝试
User.findOneAndUpdate(筛选,更新,{new:true},(err,doc)=>{…})
啊,这很有效!你介意解释一下原因吗?你可以在这里读到: