更新:为什么在 mongodb 中编辑后用户角色没有改变?

UPDATE: why is user role not changing after edit in mongodb?

我正在尝试通过 nodejs/expressjs 和 mongodb 使身份验证用户部分,其中用户将具有不同的角色,用户的参数将保存在 mongodb 中。如果为每个用户登录,他们将默认保存为“用户”。编辑后,其角色将更改为管理员或版主,此角色更改也将在 mongodb 中更新。

这是我在节点中的用户模式。js/Express.js:

 const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
    minlength: 8,
  },
  displayName: {
    
    type: String,
  },
  role: {
    type: String,
    enum: ['user', 'moderator', 'admin'],
    default: 'user',
  },
  resetLink: {
    data: String,
    default: "",
  },
});

module.exports=User=mongoose.model("user",userSchema) 

此处router.put用于编辑和更新角色:

    router.put("/:username/newrole",async(req,res)=>{
  
let role,username;

try {
  username = req.params.username;
  
   console.log(username);

  
  
const result = await User.updateOne(
  { username: req.body.username },
  { $set: { role: req.body.role } }
);  

  console.log("result = ", result);

  res.status(200).json({ msg: "User role has been updated successfully!" });
} catch(e) {
  if (User == null) {
    console.log(e)
    res.status(400).json({ msg: "no such username found!" });
  } else {
    User: User, 
    console.log(e);
    res.status(405).json({ msg: "Error updating!" });
  }
}
 
})

我正在使用 postman 检查代码。 url 用于编辑的是 http://localhost:5000/users/admin/newrole,其中 admin 是要更改角色的用户的用户名。在 post 的正文行中,我给出的输入如下:

{
"role":"user"
} 

但输出显示用户角色已成功更改,但 console.log(结果):

result =  {
  n: 0,
  nModified: 0,
  opTime: {
    ts: Timestamp { _bsontype: 'Timestamp', low_: 2, high_: 1611010685 },
    t: 7
  },
  electionId: 7fffffff0000000000000007,
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 2, high_: 1611010685 },
    signature: { hash: [Binary], keyId: [Long] }
  },
  operationTime: Timestamp { _bsontype: 'Timestamp', low_: 2, high_: 1611010685 }
}

 

这里是

的快照

数据库用户角色显示 role: null 假设要更改为“用户”。我哪里弄错了?

请告诉我

当您执行 user.updateOne({role: req.body.role}); 时,响应不是用户更新而是类似于 { ok: 0, n: 0, nModified: 0 }.

所以下一行 user.save(); 不是预期的行为。

您可以只使用一个数据库调用,而不是使用三个数据库调用:

await user.findOneAndUpdate({ username: username },{$set:{role: req.body.role}})

你在这里做的是:对于 username 等于 - 你从 req.body.username 加载的用户名的文档 - 然后将值 role 设置为值 req.body.role.

终于解决了。以下是更新角色的代码:

router.patch('/:id/update',async(req,res)=>{
 
try {
 const user=await User.updateOne({_id:req.params.id},{$set:{role:req.body.role}},{
    new:true
  })
  console.log(req.body.role); 
} catch (e) {
  console.log(e)
}
})

在邮递员中,我必须使用 x-www-form-urlencoded,其中我选择了键作为角色,值是管理员或用户或我想要的任何枚举。并且请求 url 必须包含 _id 编号,因为我已经用它过滤了,这将是一个补丁请求。

成功了。

但比 J.F。求助。你的聊天帮助我了解了 mongoose 和 mongodb 命令以及 nodejs/expressjs 处理路由。