node.js - 在 mongoose 中为用户分配角色
问题描述
我正在尝试使用 mongoose 更新用户角色。我一直在使用猫鼬 findOneAndUpdate 但无法更新角色。我没有收到任何错误消息,但我在更新之前获得了文档。所以我做了一些研究并尝试添加{new:true}
,但它没有改变任何东西。然后我看到有人使用聚合查询$push
,但也没有用。
我已经多次重写了这个查询,但没有给我预期的结果
exports.changeRole = async (req, res) => {
User.findOneAndUpdate(
{ id: req.param.userId },
{
$push: {
$set: { "roles[0].name": req.body.name },
},
},
{ new: true }
)
.populate("roles", "-__v")
.exec((err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
};
我如何发送邮递员
{
"roles": ["Admin"]
}
这是我在控制台中得到的:
{
roles: [ { _id: 606242fa3bcbc13305bee567, name: 'user' } ],
_id: 606307a839a54f7982f8ff84,
username: 'before',
email: 'before@gmail.com',
password: '$2a$/lvMv80IPZe9FSm',
__v: 1
}
我有一个名为 User 的模型
const userSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
min: 6,
max: 255,
},
email: {
type: String,
required: true,
min: 6,
max: 255,
},
password: {
type: String,
required: true,
min: 6,
max: 15,
},
roles: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Role",
},
],
},
{ timestamp: true }
);
此用户模型引用 Role.js。objectId:s 的数组。因此,如果它们不存在,我会自动创建四个角色文档。每个用户都在引用其中一个文档(角色)
const Role = mongoose.model(
"Role",
new mongoose.Schema({
name: String,
})
);
解决方案
我想的不对。我不需要更改填充的文档,只需要更改它在我roles:[]
的 User.js中引用的 objectId。使用 $set 更改字段并使用 $push to 添加新值。
exports.changeRole = async (req, res) => {
await User.findOneAndUpdate(
{ id: req.params.userId },
{
$set: { roles: req.body.roles },
},
{ new: true }
)
.populate("roles")
.then((data) => {
if (!data) return res.status(404).send("Not found");
res.send(data);
})
.catch((err) => {
return res.status(500).send({ message: err.message });
});
};
推荐阅读
- python - Mongodb查询或ETL工具
- python - 如何打开 python NLTK 下载器
- visual-studio-code - 如何设置 VSCode 以将花括号放在同一行?
- complexity-theory - 确定 Big-Oh / Big-Theta 或 Big-Omega
- java - 不包含空格和至少一个“*”的字符串的正则表达式
- android - TimePickerDialog 中的 AM/PM 文本中断
- java - Java 方法和数组
- mysql - 如何在mysql触发器中将点(。)连接到像pic.jpeg这样的字符串?
- mysql - 如何将一列 INNER JOIN 连接到两个不同的列?
- objective-c - FFmpeg 跳转到最近的帧