0

I am generator-rest generator of yeoman which is using mongoose, bodymen and express and I have updated the default User schema provided in the generator.

When I send request from Postman I am getting error Cast to Array failed for value \"[object Object]\" at path \"corp_locations\"

After Trying all possible ways in multiple posts, I am not able to fix this error.

Here is my schema

const locationsSchema = new Schema({
  location_name: String,
  address: String,
  area: String,
  pincode: Number
})

const userSchema = new Schema({
  user_id: {
    type: String,
    required: [true, 'User Id is required.'],
    unique: true,
    trim: true,
    match: [/^\d{10}$/, 'User Id is invalid.']
  },
  password: {
    type: String,
    required: [true, 'Password is required.'],
    minlength: 6
  },
  email: {
    type: String,
    match: [/^\S+@\S+\.\S+$/, 'Email is invalid.'],
    required: [true, 'Email is required.'],
    unique: true,
    trim: true,
    lowercase: true
  },
  corp_locations: [locationsSchema],
  created_by: String,
  updated_by: String
}, {
  timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }
})

The post method

router.post('/',
  master(),
  body(schema.tree)
  create)

The create method of controller

export const create = ({ bodymen: { body } }, res, next) =>
  User.create(body)
    .then((user) => user.view(true))
    .then(success(res, 201))
    .catch((err) => {

      res.status(409).json(validationMessages(err))
    })

Here is the json sent from Postman

{
    "user_id" : "1000000002",
    "password" : "password",
    "email" : "[email protected]",
    "corp_locations" : [
        {
            "location_name": "loc1",
            "address": "arrd1",
            "area": "area1",
            "pincode": "9092230"
        }
    ]
}

Please let me know what I am doing wrong.

1 Answer 1

3

After a lot of google, I found this.

https://github.com/diegohaz/bodymen/issues/1

It was an issue with bodymen and the post method should look like this.

router.post('/',
  master(),
  body({user_id, email, password, user_type, corp_locations: [Object]}),
  create)

schema.tree works fine for simple document but for nested document we have to specify the fields separately, lot of unnecessary code but that is how it works.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.