André
André

Reputation: 783

Cast to Embedded failed for value when using SubDocs in MongoDB

I was using this on my user schema to be able to have a one to many relationships with the role collection but after I've tried to change it, I'm getting this error. I've searched for answers before but unfortunately, it doesn't answer my question.

Code before on the UserSchema :

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

Code after:

role: RoleSchema

Code on my RoleSchema:

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

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

module.exports = {Role}

The complete error message through Postman:

{
    "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"
}

Upvotes: 1

Views: 2967

Answers (1)

Hardik Shah
Hardik Shah

Reputation: 4200

You just need to pass role : {"name" : "admin"} as your schema expecting object along with String value.

This will store data like this:

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

Upvotes: 2

Related Questions