首页 > 解决方案 > 在 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,
  })
);

标签: node.jsarraysmongoosemongodb-querymongoose-populate

解决方案


我想的不对。我不需要更改填充的文档,只需要更改它在我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 });
    });
};

推荐阅读