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

时间:2014-02-05 22:51:11

标签: javascript node.js mongodb mongoose

我有一个MongooseJS架构,其中父文档引用一组子文档:

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

为了进行测试,我想在父文档中使用一些虚拟值填充项目数组,而不将它们保存到MongoDB:

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

但是当我尝试将此对象推入数组时,只存储了_id

parent.items.push(item);
console.log("...parent.items[0]: " + parent.items[0]);
console.log("...parent.items[0].Blah: " + parent.items[0].Blah);

输出:

...parent.items[0]: 52f2bb7fb03dc60000000005
...parent.items[0].Blah:  undefined

我可以用某种方式做相同的`.populate('items')吗? (即:从MongoDB读取文档时填充数组的方式)

1 个答案:

答案 0 :(得分:5)

在您的问题详细信息中,您自己的调查显示您正在推送文档,因为您可以找到_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 ,这会引起疑问:

“您的架构中是否定义了'Blah'访问者?”

所以要么不是,要么定义中存在类似的问题。