CastError:Cast to Array的值失败

时间:2016-04-06 12:58:15

标签: node.js mongoose

当我从post收到数据并尝试解析它时出现错误。

这是关于这个问题的详细信息:

我有两种模式:

var tags = require('../tag/tag.model'),
  mongoose = require('mongoose'),
  Schema = mongoose.Schema;

var OpportunitiesSchema = new Schema({
    employeeTitle: String,
    tagline: Boolean,
    description:String,
    location:String,
    isPreferred:Boolean,
    tags: [
      {
        type:Schema.Types.ObjectId,
        ref:'Tag'
      }
    ]
});

module.exports.opportunities = mongoose.model('Opportunities', OpportunitiesSchema);

我还有另一个模特:

var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

var TagSchema = new Schema({
  id: Number,
  name: String
});

module.exports = mongoose.model('Tag', TagSchema);

我的功能如下:

var Opportunities = require('./opportunities.model').opportunities;
exports.create = function(req, res) {
  //addOpportunitites.save(req.body, function(err, tag) {
  //    if(err) { return handleError(res, err); }
  //    return res.json(201, tag);
  //});

  var newOpportunity = new Opportunities(req.body);

  newOpportunity.save(function(err) {
    if(err) {
      console.log(err);
    } else {
      return res.json(201);
    }

  })
};

当我发送这样的数据时:

{
  "employeeTitle": "Digital Agency Employee, downtown Chicago",
  "tagline": "My company is offering $1000 referral bonus and I'll give you half!",
  "description": "<p>Looking for someone who has the following abilities: <ul><li></li></ul></p>",
  "location": "",
  "tags": [
    545454,45467
  ]
}   

有一个错误:

{
    [ValidationError: Opportunities validation failed]
    message: 'Opportunities validation failed',
    name: 'ValidationError',
    errors: {
        tags: {
            [CastError: Cast to Array failed for value "545454,45467" at path "tags"]
            message: 'Cast to Array failed for value "545454,45467" at path "tags"',
            name: 'CastError',
            kind: 'Array',
            value: [Object],
            path: 'tags',
            reason: undefined
        }
    }
}

1 个答案:

答案 0 :(得分:2)

tags中,您发送了Numbers,可能是标记模型中的id,但在Opportunities模型中,您正在存储ObjectId }},这是由mongo生成的_id