Impossible .push () sub-document into Mongoose array

I have a MongooseJS schema where the parent document refers to a set of subdocuments:

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

For testing, I would like to populate an array of elements in the parent document with some dummy values ​​without saving them in MongoDB:

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

However, when I try to insert this object into an array, only that is saved _id:

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

Is there any way to make the equivalent of `.populate ('items')? (i.e.: way to populate an array when reading a document from MongoDB)

+3
source share
1 answer

, , _id . . :

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 );

, , childSchema.

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

, , none , :

" " " ?"

, , .

+5

All Articles