Mongoose model Schema with reference array: CastError: Cast to ObjectId failed for value “[object Object]”

前端 未结 2 776
甜味超标
甜味超标 2021-02-08 04:34

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         


        
2条回答
  •  無奈伤痛
    2021-02-08 04:53

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

提交回复
热议问题