CastError:投射到数组失败的值
当我从post收到数据并尝试parsing它时,出现错误。
这是关于这个问题的细节:
我有两个模型:
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);
我的function是这样的:
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 } } }
在tags
,你发送的是Numbers
,大概是标签模型中的id
,但是在Opportunities
模型中,你存储的是ObjectId
,它是由mongo生成的_id
。