2017-10-17 1 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를 채우려 앞의 예에서

{phone : 000911, 
code: :{code:String, 
name_id: refid: schema One} 

을하는 것이 가능할까요?

몽구스와
+0

조회 https://stackoverflow.com/questions/9621928/how-do-i-query-referenced- $ 사용해보십시오 objects-in-mongodb/39476690 # 39476690 – sidgate

+0

스키마 3 _code_ : refid : 스키마 1 또는 2? 또한 몽구스를 사용하고 있습니까? – TGrif

+0

스키마 3 개의 코드가 스키마 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

그리고 다른 인구가 필요한 경우 제로 스키마라고 가정 해 봅시다. 3에서 2를 하나의 영으로 채울 필요가있었습니다 – motchezz

+0

이는 배열에도 적용됩니다. 세 번째 레벨을 추가해야하는 경우 다른 도트 속성을 추가하기 만하면됩니다. [populate] (http://mongoosejs.com/docs/populate.html)를 참조하십시오. – TGrif