Mongoose: subdocument CastError: cast to array

I have two schemas: One schema (parent):

var slide = require('../model/slide');

var slidesetSchema = new Schema({
    name: String,
    dataID: Schema.Types.ObjectId,
    slides: [slide]
});

      

and the child schema:

var slideSchema = new Schema();
// use this method for a recursive definiton
// src https://groups.google.com/forum/#!topic/mongoose-orm/0yUVXNyprx8
slideSchema.add({
    no: Number,
    depth: Number,
    audio: [{
        name: String,
        dataID: Schema.Types.ObjectId
    }],
    //subslides: [slideSchema] <- this will be the next step if the other problem is solved
    // it will be used to create a tree like structure
});

      

I have the following situation, a user uploads a pdf file and then my nodejs node creates a new entry (slideshow) for the file, and for each page, it has to create a slide and store it in the slideshow. Finally, all this needs to be saved in db:

var set = new slideset();
var slides = [];

for (var i = 1; i <= pagecount; i++) {
    var s = new slide({no: i, depth: 1, audio: []});
    slides.push(s);
    // set.slides.push(s); <-- throws "can't call push of undefined",
    // well here http://mongoosejs.com/docs/subdocs.html they just do the same thing.. why doesn't it work for me?!
}
set.slides = slides;
// some other stuff, like writestream to save the file into db, set set.name and dataID
writestream.on('close', function (file) {
     // save schema
     set.save(function (err) {
         console.err(err);
     }
});

      

the "save" function throws the following error:

ValidationError: CastError: Cast to Array failed for value "{...},{...},..." at path "slides"

      

I tried various possible solutions I found here on stackoverflow but none of them worked. Hope you can help me :-)

+3


source to share


1 answer


You tried:

var Audio = new Schema({
       name: String,
       dataID: Schema.Types.ObjectId    
});

      

and then



slideSchema.add({
    no: Number,
    depth: Number,
    audio: [Audio]
});

      

?

0


source







All Articles