2017-07-24 193 views
0

我得到了这样的事情:猫鼬文档不填充

let fooSchema = new mongoose.Schema({ 
    bars: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Bar' }], 
}); 

let barSchema = new mongoose.Schema({ 
    sth1: String, 
    sth2: String, 
    sth3: String, 
}); 

两种模式在不同的文件并导出为猫鼬模型。

所以我有一个foo文件空bars阵列和一个bar文件,例如:

let foo = new Foo({ bars: [] }); 
let bar = new Bar({ sth1: "1", sth2: "2", sth3: "3" }); 

后来,当我推barfoo小号bars和控制台日志这阵我:

foo.bars.push(bar); 
console.log(foo.bars); 
//it outputs: 
["59760dcbe3a7e31c2693ce47"] 

所以foo.bars只有ID。 我应该怎么做才能在这个数组中有整个文档(没有保存,然后找到并填充这个字段)?

我想实现的是:

foo.bars.push(bar); 
console.log(foo.bars); 
[{ _id: 59760dcbe3a7e31c2693ce47, sth1: "1", sth2: "2", sth3: "3" }] 

回答

0

您使用的人口,但它听起来像是你想使用sub documents

let barSchema = new mongoose.Schema({ 
    sth1: String, 
    sth2: String, 
    sth3: String, 
}); 

let fooSchema = new mongoose.Schema({ 
    bars: [ barSchema ] 
}); 

由于是为barSchema没有关联的模型,你不能实例化bar文档。您可以使用这样的事情:

let foo = new Foo({ bars: [ { sth1: "1", sth2: "2", sth3: "3" } ] }); 

或者:

let foo = new Foo; 
foo.bars.create({ sth1: "1", sth2: "2", sth3: "3" });