问题描述
我正在尝试使用 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
}
const userSchema = new mongoose.Schema(
{
username: {
type: String,required: true,min: 6,max: 255,email: {
type: String,password: {
type: String,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,})
);
解决方法
我的想法不对。我不需要更改我填充的文档,只需要更改它在 User.js 中的 roles:[]
中引用的 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 });
});
};