2012-04-02 5 views
5

몽구스의 임베디드 및 링크 된 문서에 대한 여러 게시물을 읽고 다시 읽었습니다. 어느 경우 매우 자주 변경되지 않습니다 CategoriesSchema, ColorsSchema 및 MaterialsSchema에 정의중첩 된 몽구스 임베디드 문서를 채우는 방법

var CategoriesSchema = new Schema({ 
    year   : {type: Number, index: true}, 
    make   : {type: String, index: true}, 
    model   : {type: String, index: true}, 
    body   : {type: String, index: true} 
}); 

var ColorsSchema = new Schema({ 
    name   : String, 
    id    : String, 
    surcharge  : Number 
}); 

var MaterialsSchema = new Schema({ 
    name    : {type: String, index: true}, 
    surcharge   : String, 
    colors    : [ColorsSchema] 
}); 

var StyleSchema = new Schema({ 
    name    : {type: String, index: true}, 
    surcharge   : String, 
    materials   : [MaterialsSchema] 
}); 

var CatalogSchema = new Schema({ 
    name     : {type: String, index: true}, 
    referenceId   : ObjectId, 
    pattern    : String, 
    categories   : [CategoriesSchema], 
    description   : String, 
    specifications  : String, 
    price    : String, 
    cost    : String, 
    pattern    : String, 
    thumbnailPath  : String, 
    primaryImagePath : String, 
    styles    : [StyleSchema] 
}); 

mongoose.connect('mongodb://127.0.0.1:27017/sc'); 
exports.Catalog = mongoose.model('Catalog', CatalogSchema); 

데이터 : 내가 읽은 것을, 나는 그것이 다음과 같은 스키마 구조를 가지고하는 것이 최선이 될 것이라고 결론을 내렸다 기초. 여러 범주, 색상 및 재료가 있지만 그 수가 많지는 않지만 Catalog에서 독립적으로 찾을 필요가 없기 때문에 Catalog 모델의 모든 데이터를 보유하는 것이 더 좋을 것이라고 결정했습니다.

하지만 데이터를 모델에 저장하는 것에 대해 완전히 혼란 스럽습니다. 여기에 내가 난처한 상황에 빠진 얻을 어디에 :

var item = new Catalog; 
item.name = "Seat 1003"; 
item.pattern = "91003"; 
item.categories.push({year: 1998, make: 'Toyota', model: 'Camry', body: 'sedan' }); 
item.styles.push({name: 'regular', surcharge: 10.00, materials(?????)}); 

item.save(function(err){ 

}); 

을 나는 소재와 색상 포함 된 문서에 데이터를 얻을 수있는 방법이 같은 중첩 된 내장 된 스키마와 함께?

.push() 메서드는 중첩 된 문서에 사용할 수없는 것 같습니다.

답변

7

포함 된 문서 배열에는 push 메서드가 있습니다.

var item = new Catalog; 
item.name = "Seat 1003"; 
item.pattern = "91003"; 
item.categories.push({year: 1998, make: 'Toyota', model: 'Camry', body: 'sedan' }); 

var color = new Color({name: 'color regular', id: '2asdfasdfad', surcharge: 10.00}); 
var material = new Material({name: 'material regular', surcharge: 10.00}); 
var style = new Style({name: 'regular', surcharge: 10.00}); 

은 다음 부모에 포함 된 각 문서를 밀 수 : 이미하고있는 곳

material.colors.push(color); 
style.materials.push(material); 
item.styles.push(style); 

그럼 당신은 당신으로 전체 오브젝트를 데이터베이스에 저장할 수 있습니다 간단히 처음 item (가) 생성 한 후 포함 된 문서를 추가 :

item.save(function(err){}); 

그게 전부 야! 그리고 임베디드 DocumentArrays가 있습니다.

코드에 대한 몇 가지 다른 참고 사항으로 카탈로그 모델에 pattern 두 번 있습니다. 그리고 다른 모델 유형에 액세스하려면 다음을 내보내기해야합니다.

exports.Catalog = mongoose.model('Catalog', CatalogSchema); 
exports.Color = mongoose.model('Colors', ColorsSchema); 
exports.Material = mongoose.model('Materials', MaterialsSchema); 
exports.Style = mongoose.model('Style', StyleSchema); 
+0

컬렉션에 카탈로그가 많이있는 경우. 우리는 어떻게 특정 id에 밀을 것인가 ?? –

관련 문제