Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Can';t.将()子文档推入Mongoose数组_Javascript_Node.js_Mongodb_Mongoose - Fatal编程技术网

Javascript Can';t.将()子文档推入Mongoose数组

Javascript Can';t.将()子文档推入Mongoose数组,javascript,node.js,mongodb,mongoose,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', itemS

我有一个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";
但是,当我尝试将此对象推入数组时,仅存储
\u 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中读取文档时填充数组的方式)

在您的问题详细信息中,您自己的调查显示您正在按您可以找到的
\u 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();
现在,这将清楚地表明,没有定义任何访问器,这带来了问题:

“架构中是否定义了“Blah”访问器?”


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

在我的测试中,由于测试的工作方式,我没有调用parent.save()。我怀疑这就是我无法访问子对象的原因问题不在于save(),而在于模式定义。如我所示,尝试上面的代码或使用空模式对象的代码,您将看到所有访问器都失败<需要在您的架构中定义code>Blah。我没有工作,我尝试了findOne并使用save()推送到该子文档。它创建新记录,而不是将新项推送到子文档