【问题标题】:UPDATE: why is user role not changing after edit in mongodb?更新:为什么在 mongodb 中编辑后用户角色没有改变?
【发布时间】:2021-04-23 03:44:42
【问题描述】:

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

这是我在 node.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!" });
  }
}
 
})

我正在使用邮递员检查代码。编辑的 url 是 http://localhost:5000/users/admin/newrole,其中 admin 是要更改角色的用户的用户名。在帖子的正文行中,我输入如下:

{
"role":"user"
} 

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

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

 

这是的快照

数据库用户角色显示角色:null,假设将更改为“用户”。我在哪里犯错了?

请告诉我

【问题讨论】:

    标签: node.js mongodb express node-modules nodejs-server


    【解决方案1】:

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

    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。

    【讨论】:

      【解决方案2】:

      当您执行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 的值。

      【讨论】:

      • 输出仍然显示相同: { "msg": "no such username found!"我正在添加我的数据库的快照,以便了解用户的保存方式
      • 不存在具有该用户名的用户
      • 但在 res.status(400) 错误消息行之前,console.log(username) 显示未定义,console.log(role) 也显示未定义
      • 尝试 { 用户名 = req.body.username; //等待用户.save(); await user.findOneAndUpdate( { username: username }, { $set: { role: req.body.role } } ); console.log(role) //user.save();控制台日志(角色); res.status(200).json({ msg: "用户角色更新成功!" }); } :这是您的建议之后的代码。似乎在 try/catch 中,尝试无法找到我提供的用户名。我在nodejs中搜索了slug,上面写着没有必要使用它。所以用户名的重定向是个好主意还是我应该寻找用户_id?
      • 捕获异常并执行console.log(e) 看看是什么错误。
      猜你喜欢
      • 2022-01-13
      • 1970-01-01
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      相关资源
      最近更新 更多