2017-11-22 1 views
0

좋아 내가 events.js기로 eventSchema와 파일 그래서 : 장소의 스키마MongoDB의 객체 타입/중첩 된 스키마

var eventSchema = mongoose.Schema({ 
name:{ 
    type: String, 
    //required: true 
venue:{ 

} 
}); 

과 venue.js :

var에 몽구스 =이 (요구를 '몽구스 ');

제 질문은 어떻게 이벤트 스키마의 장소를 현장 스키마에 링크시킬 수 있습니까? 따라서 기본적으로 새로운 이벤트를 만들 때 장소 목록에있는 장소 만 추가 할 수 있습니다. 미리 감사드립니다!

+0

어쩌면이 https://stackoverflow.com/questions/18001478/referencing-another-schema-in-mongoose –

답변

1

id로 연결할 수 있습니다. 이벤트 스키마에 '장소'필드를 모두 추가 할 필요는 없습니다. 당신은 몽구스를 사용하고 있기 때문에

var eventSchema = mongoose.Schema({ 
    name:{ 
    type: String, 
    //required: true 
    }, 
    venue_id: Schema.Types.ObjectId, 
}); 

, 당신은 할 수 있습니다 필드 populate 방법을 사용

venue_id: { type: Schema.Types.ObjectId, ref: 'Venue' } 

같은.

인구 자동 (venue_id 일치 문서이다) 다른 집합 (S)에서문서 (들)와 함께 문서 (venue_id 인)를 지정된 경로 의 교환 과정이다.

당신은 그냥 venue_id하지, venue_id 일치 장소의 문서와 이벤트 문서를 반환합니다

event. 
    findOne({ name: 'somename' }). 
    populate('venue'). 
    exec(function (err, event) { 
    if (err) return handleError(err); 
}); 

처럼 사용할 수 있습니다.

+0

이 올바른 구문입니다 도움이 될 것입니다? \t 장소 : –

+0

{\t \t venue_id : { \t \t \t 유형 \t을 Schema.Types.ObjectId}} 장소 : {\t venue_id {유형 : Schema.Types.ObjectId}}에 올바른 구문 아니다. 당신이 원하는 것은 장소 스키마를 참조하는 것입니다. venue_id 필드는 내 응답과 같은 장소 수집 ID를 보유 할 수 있습니다. 또는 좀 더 구체적으로 지정하려면 venue_id와 같은 필드를 만듭니다. {{type : mongoose.Schema.Types.ObjectId, ref : 'Venue'}. – godsenal

+0

populate 메서드가 어떻게 작동하는지 좀 더 설명해 주시겠습니까? 이 인스턴스에서 어떻게 사용해야합니까? 감사!! –

0

@godsnam이주는 대답은 정확하지만 스키마에서 참조를 사용하고자 할 때입니다. 참조를 사용하지 않으려면이 방법이 도움이 될 수 있습니다.

아래와 같이 작성하여 eventSchema에서 venueSchema를 연결할 수 있습니다.

var venueSchema = mongoose.Schema(
    { 
     name: { 
      type: String, 
      //required: true 
     }, 
     postcode: { 
      type: String, 
      //required: true 
     }, 
     town: { 
      type: String, 
      //required: true 
     } 
    }); 

var eventSchema = mongoose.Schema({ 
    name: { 
     type: String, 
     //required: true 
    }, 
    venue: venueSchema 
}); 
+0

venueSchema가 같은 폴더에있는 다른 파일에있는 경우 어떻게해야합니까? –

+0

당신은 할 수 require (schemaPath); –

+0

좋아, 이제 끝냈다 : Venue = require ('./ venues'); events.js 파일에서 eventSchema에 다음을 추가했습니다. venue : venueSchema하지만 터미널에서 referenceError가 발생합니다. venueSchema가 정의되지 않았습니다./ –

관련 문제