javascript - MongoDB: Store array of models -
i have declared following models:
banana
var banana = new mongoose.schema({ src: { type: string, max: 1000, default: "yabadaba" });
user
var user = new mongoose.schema({ name: string, bananas: [banana] });
and have problems inserting data user collection. here's code:
var data = [{ name: "batman", bananas: [ new banana({src: "nananana"}), new banana({src: "nana"}) ] }, { name: "robin", bananas: [ new banana({src: "meh"}) ] }]; for(var i=0, arrlen=data.length; i<arrlen; i++){ var item = new user(data[i]); item.save(); }
and throws error...
casterror: cast array failed value "..." @ user.bananas. name: casterror, kind: 'array', value: [object], path: user.bananas, reason: [object]
as did not need store bananas db, created workaround this. if necessary store bananas separately, possible reference them via object id.
so removed bananas model , modified user model follows.
user
var user = new mongoose.schema({ name: string, bananas: [{ src: { type: string, max: 1000, default: "yabadaba" } }] });
i inserted values follows:
var data = [{ name: "batman", bananas: [ {src: "nananana"}, {src: "nana") ] }, { name: "robin", bananas: [ {src: "meh"} ] }]; for(var i=0, arrlen=data.length; i<arrlen; i++){ var item = new user(data[i]); item.save(); }
and seems working.
Comments
Post a Comment