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

24,657

Solution 1

Your article schema expects an array of ObjectId:

var ArticleSchema = new Schema({
  ...
  categories: [{ 
    type: Schema.Types.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 ] }

Solution 2

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);
Share:
24,657
Race
Author by

Race

Android programer. Image processing. Computer vision

Updated on June 20, 2021

Comments

  • Race
    Race almost 3 years

    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 ObjectId failed for value "[object Object]" at path "categories"]
      message: 'Cast to ObjectId failed for value "[object Object]" at path "categories"',
      name: 'CastError',
      type: 'ObjectId',
      value: [ [object Object] ],
      path: 'categories' }
    

    Could any one help me out? Related code shows bellow:

    The Article model defined like this:

    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.ObjectId, 
        ref: 'Category' }]
    });
    mongoose.model('Article', ArticleSchema);
    

    And the Category model defined like this:

    var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
    var CategorySchema = new Schema({
      parent: {
        type: Schema.ObjectId,
      },
      name: String,
      subs: [CategorySchema]
    });
    mongoose.model('Category', CategorySchema);
    

    When I create a new Article and save it like this:

    exports.create = function(req, res) {
      console.log(req.body);
      var article = new Article(req.body);
      article.user = req.user;
      console.log(article);
      article.save(function(err) {
        if (err) {
            console.log(err);
            return res.jsonp(500, {
                error: 'Cannot save the article'
            });
        }
        res.jsonp(article);
      });
    };
    

    When called the create function, the console.log() output shows bellow:

    // console.log(req.body);
    { title: 'This is title',
      content: '<p>content here</p>',
      categories:
       [ { _id: '53c934bbf299ab241a6e0524',
         name: '1111',
         parent: '53c934b5f299ab241a6e0523',
         __v: 0,
         subs: [],
         sort: 1 } ],
      updated: [ 1405697477413 ] }
    
    // console.log(article);
    { 
      title: 'This is title',
      content: '<p>content here</p>',
      _id: 53c93dc5b1c3b8e80cb4936b,
      categories: [],
      created: Fri Jul 18 2014 23:31:17 GMT+0800 (中国标准时间) }
    
    // console.log(err);
    { [CastError: Cast to ObjectId failed for value "[object Object]" at path "categories"]
      message: 'Cast to ObjectId failed for value "[object Object]" at path "categories"',
      name: 'CastError',
      type: 'ObjectId',
      value: [ [object Object] ],
      path: 'categories' }
    

    I have googled a lot, but without luck. Please help me!


    Update: Thank for Gergo's answer. But if I update the exist article with the almoset the same code, it works OK! Why? Codes shows bellow:

    var mongoose = require('mongoose'),
        Category = mongoose.model('Category'),
        _ = require('lodash');
    
    exports.update = function(req, res) {
    console.log(req.body);
    var article = req.article;
    article = _.extend(article, req.body);
    console.log(article);
    article.save(function(err) {
        if (err) {
            return res.jsonp(500, {
                error: 'Cannot update the article'
            });
        }
        res.jsonp(article);
    
      });
    };
    

    The output like this:

    // console.log(req.body);
    { _id: '53ca42f418bfb23c1e04df02',
        summary: 'tttt',
        title: 'tt',
        content: '<p>tttt</p>',
        __v: 2,
        categories: [ { _id: '53c934bbf299ab241a6e0524', name: '1111' } ],
        created: '2014-07-19T10:05:40.183Z'
    }
    
    // console.log(article);
    { _id: 53ca42f418bfb23c1e04df02,
        title: 'tt',
        content: '<p>tttt</p>',
        __v: 2,
        categories: [ { _id: 53c934bbf299ab241a6e0524, name: '1111', subs: [], sort: 0
        } ],
        created: Sat Jul 19 2014 18:05:40 GMT+0800 (中国标准时间) 
    }
    

    This works ok.

  • Race
    Race almost 10 years
    Thank you. But If I update a exist article with almost the same code, it works ok. I post the code and log in the question, would you please help me check it?