2017-07-24 256 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" });