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

前端 未结 2 736
甜味超标
甜味超标 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: '<p>content here</p>',
      categories: [ '53c934bbf299ab241a6e0524' ],
      updated: [ 1405697477413 ] }
    
    0 讨论(0)
  • 2021-02-08 05:13

    Please use mongoose.Schema.Types.Mixed as data type of categories. I had the same issue with saving data array. It works for me.

    var mongoose = require('mongoose'),
        Schema = mongoose.Schema;
    
    var ArticleSchema = new Schema({
        created: { type: Date, default: Date.now },
        title: String,
        content: String,
        summary: String,
        categories: [{type: Schema.Types.Mixed }]
    });
    
    mongoose.model('Article', ArticleSchema);
    
    0 讨论(0)
提交回复
热议问题