Hi everybody,
Please I have an error when I try this code s.items.push(_item);
I have two models :
var ItemSchema = new Schema(
{
title : String
}
);
mongoose.model('Item', ItemSchema)
and
var SurveySchema = new Schema(
{
title : {
type : String,
default : 'Title'
},
image : {
type : String
},
author : {
type : ObjectId,
ref : 'User',
childPath : 'surveys'
},
items : [ Item ]
},
{
collection : 'surveys'
}
);
That is the error :
/usr/local/lib/node_modules/mongoose/lib/types/array.js:108
return this._schema.caster.cast(value, this._parent, false)
^
TypeError: Object {} has no method 'cast'
at Array.MongooseArray._cast (/usr/local/lib/node_modules/mongoose/lib/types/array.js:108:30)
at Object.map (native)
at Array.MongooseArray.push (/usr/local/lib/node_modules/mongoose/lib/types/array.js:262:23)
at /home/mael-fosso/www/questan/node.js/controllers/survey.js:86:25
at Array.map (native)
at Promise.<anonymous> (/home/mael-fosso/www/questan/node.js/controllers/survey.js:84:41)
at Promise.<anonymous> (/usr/local/lib/node_modules/mongoose/node_modules/mpromise/lib/promise.js:177:8)
at Promise.EventEmitter.emit (events.js:95:17)
at Promise.emit (/usr/local/lib/node_modules/mongoose/node_modules/mpromise/lib/promise.js:84:38)
at Promise.fulfill (/usr/local/lib/node_modules/mongoose/node_modules/mpromise/lib/promise.js:97:20)
how to solve it please ?
Can you clarify what version of mongoose you're using and what _item
is in your example (preferably with require('util').inspect()
output)?
The description of _item
by using
console.log(util.inspect(_item, {showHidden: true, depth: null}));
is
{ title: 'Label', _id: 55185e2fce8f87c67728039d }
The version of mongoose is 3.8.20
Thanks.
So mongoose doesn't support array of models as a schema type. What you need to do is:
var SurveySchema = new Schema(
// ...
items: [ ItemSchema ]
// ...
);
It should work:
var SurveySchema = new Schema(
{
title : {
type : String,
default : 'Title'
},
image : {
type : String
},
author : {
type : ObjectId,
ref : 'User',
childPath : 'surveys'
},
items : [ Item.schema ] // Gets item schema
},
{
collection : 'surveys'
}
);
Most helpful comment
It should work: