【问题标题】:Cast to Array failed for value \"[object Object]\" at path路径中的值 \"[object Object]\" 转换为数组失败
【发布时间】:2017-07-24 21:04:33
【问题描述】:

我是使用 mongoose、bodymen 和 express 的 yeoman 的 generator-rest 生成器,我已经更新了生成器中提供的默认用户模式。

当我从 Postman 发送请求时,我收到错误 Cast to Array failed for value \"[object Object]\" at path \"corp_locations\"

在多个帖子中尝试了所有可能的方法后,我无法修复此错误。

这是我的架构

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' }
})

post方法

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

控制器的创建方法

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))
    })

这是 Postman 发送的 json

{
    "user_id" : "1000000002",
    "password" : "password",
    "email" : "email2@mail.com",
    "corp_locations" : [
        {
            "location_name": "loc1",
            "address": "arrd1",
            "area": "area1",
            "pincode": "9092230"
        }
    ]
}

请让我知道我做错了什么。

【问题讨论】:

    标签: mongodb express mongoose mean


    【解决方案1】:

    在google了很多之后,我找到了这个。

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

    这是 bodymen 的问题,post 方法应该是这样的。

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

    schema.tree 适用于简单文档,但对于嵌套文档,我们必须单独指定字段,很多不必要的代码,但它就是这样工作的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 2015-08-14
      • 2013-02-06
      • 2016-02-23
      • 2015-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多