在MongoDB中使用SubDocs时,强制转换为Embedded的值失败

时间:2018-07-24 12:41:37

标签: node.js mongodb mongoose

我在用户架构上使用它可以与角色集合建立一对多关系,但是在尝试对其进行更改后,出现此错误。我之前已经搜索过答案,但是很遗憾,它没有回答我的问题。

UserSchema之前的代码:

  role: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Role",
    required: true
  }

后面的代码:

role: RoleSchema

我的RoleSchema上的代码:

const RoleSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true
  }
});

const Role = mongoose.model("Role", RoleSchema);

module.exports = {Role}

通过邮递员的完整错误消息:

{
    "errors": {
        "role": {
            "message": "Cast to Embedded failed for value \"b51c9619230f72627ed729e\" at path \"role\"",
            "name": "CastError",
            "stringValue": "\"b51c9619230f72627ed729e\"",
            "kind": "Embedded",
            "value": "b51c9619230f72627ed729e",
            "path": "role",
            "reason": {
                "message": "Tried to set nested object field `role` to primitive value `b51c9619230f72627ed729e` and strict mode is set to throw.",
                "name": "ObjectExpectedError",
                "path": "role"
            }
        }
    },
    "_message": "User validation failed",
    "message": "User validation failed: role: Cast to Embedded failed for value \"b51c9619230f72627ed729e\" at path \"role\"",
    "name": "ValidationError"
}

1 个答案:

答案 0 :(得分:1)

您只需要将role : {"name" : "admin"}作为模式期望对象以及字符串值进行传递。

这将存储如下数据:

{
  "_id" : ObjectId("5b572805098d8a23a36cc62d"),
  "title" : "New Survey",
  "language" : {
    "name" : "EN",
    "_id" : ObjectId("5b572805098d8a23a36cc62e"),
    "ut" : 1532438230187.0,
    "ct" : 1532438230187.0
  },
  "ut" : 1532438230187.0,
  "ct" : 1532438230187.0,
}