Mongoose - 更新已填充文档的 objectId

问题描述

我有一个引用角色模型的用户模型。在 myFirstDatabase.roles 中,我创建了四个具有不同角色的文档。因此,例如,如果我正在填充我的一个用户,我会得到这个

"roles": [
        {
            "_id": "606242fa3bcbc13305bee567","name": "user","__v": 0
        }
    ],"_id": "606718d8cc19767df626aaa1","username": "testin","email": "jonas@gmail.com"

问题是我想将用户角色更改为另一个现有文档

{
            "_id": "606242fa3bcbc13305bee568","name": "moderator","__v": 0
        } 

我已经试过了:

exports.changeRole = async (req,res) => {
  await User.findOneAndUpdate(
    { id: req.params.userId },{
      $set: { "roles.0.name": 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 });
    });
};

但我收到一条错误消息:“message”:“无法在元素 {0: ObjectId('606242fa3bcbc13305bee567')} 中创建字段 'name'”

然后我尝试了 $push 但也许我用错了。我还编写了四种不同的查询,例如:

 exports.changeRole = async (req,res) => {
   User.findOne({ id: req.params.userId })
     .populate("roles")
     .exec(function (err,user) {
       if (err) return handleError(err);
       user.roles[0].name = "moderator";
       console.log("The role is %s",user.roles[0].name);
     
    });
 };

但我想我只是在这里更改名称,并没有真正用角色版主文档替换角色用户文档。

在我的用户模型中

roles: [
      {
        type: mongoose.Schema.Types.ObjectId,ref: "Role",],

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)