2017-10-17 186 views
0

當我需要從我的服務器獲取數據時,我在服務器中碰到了一堵牆。 以下代表我的模式:節點js,mongodb填充填充的

Schema one:{ 
name: String 
} 
Schema two:{ 
code:String, 
name_id: refid: schema One 
} 
Schema three:{ 
phone:number 
code:[refid: Schema two] 
} 

如果我需要從架構三個數據,並從對象ID中保存的代碼陣列我會用填入,我會得到通過對象ID引用的對象中的對象。 問題是可以填充填充的數據嗎? 如果填入模式3 我會得到的物體,如:

{phone : 000911, 
code: :{code:String, 
name_id: refid: schema One} 
前面的例子中,我要填充名字ID在

,這可能嗎?

+0

嘗試使用$查找https://stackoverflow.com/questions/9621928/how-do-i-query-referenced- objects-in-mongodb/39476690#39476690 – sidgate

+0

Schema是三個_code_:refid:Schema是一個還是兩個?你也使用貓鼬? – TGrif

+0

模式三的代碼是從模式2引用的,是的,我正在使用貓鼬 – motchezz

回答

1

隨着貓鼬,您可以填充點符號您的模式是這樣的:

const One = new Schema({ 
    name: String 
}) 

const Two = new Schema({ 
    code: String, 
    name: { 
    type: Schema.ObjectId, 
    ref: 'One' 
    } 
}) 

const Three = new Schema({ 
    phone: number 
    code: [{ 
    type: Schema.ObjectId, 
    ref: 'Two' 
    }] 
}) 


Three.find((err, three) => { 
    if (err) console.log(err) 
    console.log(three) 
    // => { 
    //  phone : "the phone number from schema Three", 
    //  code: { 
    //  code: "the code from schema Two", 
    //  name: "the name from schema One" 
    //  } 
    // } 
}) 
.populate('code.name') 
+0

如果代碼是一個ID數組呢? – motchezz

+0

,如果我需要另一個人羣,我們假設一個零架構,並且我需要從三到二填充到零 – motchezz

+0

這也適用於一個數組。如果您需要添加第三個級別,只需添加另一個點屬性。請參閱[填充](http://mongoosejs.com/docs/populate.html)。 – TGrif