2014-07-22 3 views
0

동적 구조로 문서를 만드는 HTML 양식이 있습니다. 다음은 사용자가 삽입 한 데이터의 일부 샘플입니다.MongoDb : 가변 구조를 사용하는 문서 및 C#

아주 간단한 문서

{ 
"name" : "Simple element", 
"notes" : "Lorem ipsum rocks", 
"values" : [ 
    { 
     "name" : "An array with 2 values", 
     "value" : [ 100,200], 
     "editable" : true 
    } 
] 

}

과 문서가 C# MongoCharp 드라이버와 NancyFX를 사용하여 MongoDB에 저장해야 더 복잡한 문서

{ 
"name" : "Complex element", 
"notes" : "Lorem ipsum rocks", 
"values" : [ 
    { 
     "name" : "A text value", 
     "value" : "ABCDEF", 
     "editable" : true 
    }, 
    { 
     "name" : "A numeric value", 
     "value" : 100, 
     "editable" : false 
    }, 
    { 
     "name" : "A array of 4 values", 
     "value" : [1,2,3,4], 
     "editable" : false 
    }, 
    { 
     "name" : "A matrix 2x4", 
     "value" : [[1,2,3,4],[5,6,7,8]], 
     "editable" : false 
    } 
] 

}

. 순간 POST가이 방식으로 구현되어 있지만 올바른 방법은 동적 구조

Post["/api/docs"] = _ => 
{ 
    //looking for better solution 
    var json = Request.Body.AsString(); 
    var item = BsonDocument.Parse(json); 
    database.GetCollection("docs").Insert(item); 
    return new Response { StatusCode = HttpStatusCode.Created }; 
}; 

와 객체를 처리 할 수 ​​있지만, GET 방법에 대한 좋은 해결책을 찾을 수없는 경우 잘 모르겠어요

Get["/api/docs"] = _ => 
{ 
    //looking for solution 
}; 

이 시나리오에서 가장 좋은 해결책은 무엇이라고 생각하십니까? 그냥 JSON으로 MongoDB를에서 문서를 반환하고자하는 경우

+0

인서트 바인딩을 사용할 수 있기 때문에, 판독 데이터가 구현 된 모듈보다

public class DocumentItem { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public String Id { get; set; } public String Name { get; set; } public String Notes { get; set; } public SubItem[] Values { get; set; } } public class SubItem { public String Name { get; set; } public Boolean Editable { get; set; } public Object Value { get; set; } } 

개체 한 어떻게 문서를 쿼리하고 싶습니까? 어떤 필드에 쿼리 하시겠습니까? –

+0

속성 (예 : 이름) 또는 단일 문서로 필터링 된 문서 목록을 _id – jitidea

+0

(으)로 되돌리고 싶습니다. 그리고 필터링 할 속성을 어떻게 알 수 있습니까? 쿼리 문자열? –

답변

0

문제를 해결하는 또 다른 방법도있다이

Get["/api/docs/{category}"] = _ => 
{ 
    var filterValue = _.category; 
    //Search the DB for one record where the category property matches the filterValue 
    var item = database.GetCollection("docs").FindOne(Query.EQ("category", filterValue)) 
    var json = item.ToJson(); 

    var jsonBytes = Encoding.UTF8.GetBytes(json); 
    return new Response 
    { 
     ContentType = "application/json", 
     Contents = s => s.Write(jsonBytes, 0, jsonBytes.Length) 
    }; 
}; 
+0

JSON 형식을 반환 MongoDB는 옵션입니다. 또한 샘플 JSON 문서를 C# 개체에 매핑하는 방법을 발견했습니다. – jitidea

1

같은 것을보십시오. 이것을 "강건 형 솔루션"이라고합시다. I는 두 생성 POCO는

Get["/api/docs/{id}"] = p => database.GetCollection<DocumentItem>("docs") 
      .FindOne(Query<DocumentItem>.EQ(x => x.Id, (string)p.id)); 

    Get["/api/docs"] = _ => database.GetCollection<DocumentItem>("docs") 
      .FindAll() 
      .ToList(); 

아래 도시 및 I이 방법

Post["/api/docs"] = _ => 
    { 
     var item = this.Bind<DocumentItem>(); 
     database.GetCollection("docs").Insert(item); 
     return item; 
    };