0

i'm creating a blog schema with array of category id,but when i try to insert data on field it's show

category_id: Cast to Array failed for value "[\'5c8a207e36e3613fe9a6ce30\',\'5c8a207e36e3613fe9a6ce30\']" at path "category_id"

my schema is

var mongoose = require('mongoose');

var blogSchema = new mongoose.Schema({
    title:{
        type:String,
        required:true
    },
    user_id:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'User'
    },
    category_id:{
        type:[mongoose.Schema.Types.ObjectId],
        ref:'Categories',
    },
    description:{
        type:String,
        required:true
    },
    is_featured:{
        type:Boolean,
        default:false
    },
    isActive:{
        type:Boolean,
        default:true
    },
    created_at:{
        type:Date,
        default:Date.now
    },
    updated_at:{
        type:String
    }
});

var Blog = mongoose.model('Blog',blogSchema);

module.exports.Blog = Blog;

also i try

category_id:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Categories',
    }],

but getting same error

Codexx
  • 37
  • 9
  • when you are inserting into collection are you using id as objectid or string? id = mongoose.Types.ObjectId('5c8a207e36e3613fe9a6ce30'); – AZ_ Mar 15 '19 at 07:17
  • i'm using postman and send id like that "category_id":"['5c8a207e36e3613fe9a6ce30','5c8a207e36e3613fe9a6ce30']", – Codexx Mar 15 '19 at 07:21
  • ohh, you need to parse the array in your code as "[]" is a string. or use "category_id":['5c8a207e36e3613fe9a6ce30','5c8a207e36e3613fe9a6ce30'] – AZ_ Mar 15 '19 at 07:24
  • or try https://stackoverflow.com/questions/12756688/is-it-possible-to-send-an-array-with-the-postman-chrome-extension – AZ_ Mar 15 '19 at 07:25
  • @AZ_ not clear understand your answer, as i understand i'm sending array using "[]" – Codexx Mar 15 '19 at 07:29
  • everything inside the quote " is a string so as "[]", if you want to insert an array you may need to remove the quotes. so it must be "category_id":['5c8a207e36e3613fe9a6ce30','5c8a207e36e3613fe9a6ce30'] – AZ_ Mar 15 '19 at 07:32
  • Thank you @AZ_ this is the problem in api data, now it's working fine – Codexx Mar 15 '19 at 07:38

0 Answers0