javascript - Can't .push() sub-document into Mongoose array -
i have mongoosejs schema parent document references set of sub-documents:
var parentschema = mongoose.schema({ items : [{ type: mongoose.schema.types.objectid, ref: 'item', required: true }], ... });
for testing i'd populate item array on parent document dummy values, without saving them mongodb:
var itemmodel = mongoose.model('item', itemschema); var item = new itemmodel(); item.blah = "test data";
however when try push object array, _id
stored:
parent.items.push(item); console.log("...parent.items[0]: " + parent.items[0]); console.log("...parent.items[0].blah: " + parent.items[0].blah);
outputs:
...parent.items[0]: 52f2bb7fb03dc60000000005 ...parent.items[0].blah: undefined
can equivalent of `.populate('items') somehow? (ie: way populate array when reading document out of mongodb)
within question details own investigation shows pushing document can find it's _id
value. not actual problem. consider code below:
var mongoose = require('mongoose'); var schema = mongoose.schema; mongoose.connect('mongodb://localhost/nodetest') var childschema = new schema({ name: 'string' }); //var childschema = new schema(); var parentschema = new schema({ children: [childschema] }); var parent = mongoose.model('parent', parentschema); var parent = new parent({ children: [{ name: 'matt' }, { name: 'sarah'}] }); var child = mongoose.model('child', childschema); var child = new child(); child.blah = 'eat shorts'; parent.children.push(child); parent.save(); console.log( parent.children[0].name ); console.log( parent.children[1].name ); console.log( parent.children[2] ); console.log( parent.children[2].blah );
so if problem isn't standing out now, swap commented line definition of childschema
.
// var childschema = new schema({ name: 'string' }); var childschema = new schema();
now that's going show none of accessors defined, brings question:
"is 'blah' accessor defined in schema?"
so either isn't or there similar problem in definition there.
Comments
Post a Comment