【发布时间】: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