I build a blog website with express.js and mongoosejs. A article may have one or more category. When I create a new article, I get error:
{ [CastError: Cast to O
Your article schema expects an array of ObjectIds:
var ArticleSchema = new Schema({
...
categories: [{
type: Schema.ObjectId,
ref: 'Category' }]
});
However req.body
contains a category object:
categories:
[ { _id: '53c934bbf299ab241a6e0524',
name: '1111',
parent: '53c934b5f299ab241a6e0523',
__v: 0,
subs: [],
sort: 1 } ]
And Mongoose can't convert the category object to an ObjectId. This is why you get the error. Make sure categories
in req.body
only contains ids:
{ title: 'This is title',
content: 'content here
',
categories: [ '53c934bbf299ab241a6e0524' ],
updated: [ 1405697477413 ] }