简体   繁体   English

不能.push()子文件进入Mongoose数组

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

I have a MongooseJS schema where a parent document references a set of sub-documents: 我有一个MongooseJS架构,其中父文档引用一组子文档:

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: 为了进行测试,我想在父文档中使用一些虚拟值填充item数组,而不将它们保存到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: 但是,当我尝试将此对象推入数组时,只存储_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

Can I do the equivalent of `.populate('items') somehow? 我能以某种方式做相当于`.populate('items')吗? (ie: the way you would populate the array when reading the document out of MongoDB) (即:从MongoDB中读取文档时填充数组的方式)

Within your question details your own investigation shows that you are pushing the document as you can find it's _id value. 在您的问题详细信息中,您自己的调查显示您正在推送文档,因为您可以找到它的_id值。 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 . 因此,如果问题现在不突出,请将注释行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?" “你的架构中是否定义了'Blah'访问器?”

So it either isn't or there is a similar problem in the definition there. 所以它要么没有,要么在那里的定义中存在类似的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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