Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't .push() sub-document into Mongoose array

I have a MongooseJS schema where a parent document references a set of sub-documents:

var parentSchema = mongoose.Schema({
    items : [{ type: mongoose.Schema.Types.ObjectId, ref: 'Item', required: true }],
...
});

For testing I'd like to populate the item array on a parent document with some dummy values, without saving them to the MongoDB:

var itemModel = mongoose.model('Item', itemSchema);
var item = new itemModel();
item.Blah = "test data";

However when I try to push this object into the array, only the _id is 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 I do the equivalent of `.populate('items') somehow? (ie: the way you would populate the array when reading the document out of MongoDB)

like image 922
Daniel Flippance Avatar asked Feb 10 '26 03:02

Daniel Flippance


1 Answers

Within your question details your own investigation shows that you are pushing the document as you can find it's _id value. But that is not the actual problem. Consider the 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 my 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 the problem isn't standing out now, swap the commented line for the definition of childSchema.

// var childSchema = new Schema({ name: 'string' });
var childSchema = new Schema();

Now that's clearly going to show that none of the accessors are defined, which brings to question:

"Is your 'Blah' accessor defined in your schema?"

So it either isn't or there is a similar problem in the definition there.

like image 58
Neil Lunn Avatar answered Feb 13 '26 17:02

Neil Lunn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!