简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM