2012-10-07 2 views
2

예제의 스키마 설명을 사용합니다.재귀 적 임베디드 - 문서 몽고를 찾기, 수정 및 제거

Comment.add({ 
    title  : { type: String, index: true } 
    , date  : Date 
    , body  : String 
    , comments : [Comment] 
}); 

var BlogPost = new Schema({ 
    title  : { type: String, index: true } 
    , slug  : { type: String, lowercase: true, trim: true } 
    , date  : Date 
    , buf  : Buffer 
    , comments : [Comment] 
    , creator : Schema.ObjectId 
}); 

의견에 몇 가지 중첩 수준이 있습니다. 중첩의 모든 수준에 적절한 주석을 찾아 내가 검색에 재귀를 만들려고 그것 (편집 삭제하거나 새 중첩 된 주석 추가) 을 어떤 행동을하지만 당신은 코멘트를 저장하거나 삭제할 수 없습니다하는 방법

BlogPost.methods.findComment = function (id, callback) { 

    var curentComment = this.comments; 
    var findComment = null; 
    var recursiveFindComment = function(comment){ 
     for(i=0;i<comment.length;i++){ 
      if(findComment){ 
       break; 
      } 
      if(comment[i]._id == id){ 
       findComment = comment[i]; 
       break;  
      }else if(comment[i].comments.length>0){ 
       findComment = recursiveFindComment(comment[i].comments) 
      } 
     } 
     return findComment; 

    } 

    if(curentComment.id(id)){ 
    callback(curentComment); 
    }else{ 
    callback(recursiveFindComment(curentComment, null)) 
    } 
} 

답변

0

MongoDb (http://www.mongodb.org/display/DOCS/Trees+in+MongoDB)에서 나무를 사용하는 것이 좋습니다. 스키마의 재귀 적 특성을 돕는 여러 가지 방법이 있습니다.

> t = db.tree 
test.tree 

> // get entire tree -- we use sort() to make the order nice 
> t.find().sort({path:1}) 
{ "_id" : "a", "path" : "a," } 
{ "_id" : "b", "path" : "a,b," } 
{ "_id" : "c", "path" : "a,b,c," } 
{ "_id" : "d", "path" : "a,b,d," } 
{ "_id" : "g", "path" : "a,b,g," } 
{ "_id" : "e", "path" : "a,e," } 
{ "_id" : "f", "path" : "a,e,f," } 
{ "_id" : "g", "path" : "a,b,g," } 

> t.ensureIndex({path:1}) 

> // find the node 'b' and all its descendents: 
> t.find({ path : /^a,b,/ }) 
{ "_id" : "b", "path" : "a,b," } 
{ "_id" : "c", "path" : "a,b,c," } 
{ "_id" : "d", "path" : "a,b,d," } 
{ "_id" : "g", "path" : "a,b,g," } 

> // find the node 'b' and its descendents, where path to 'b' is not already known: 
> nodeb = t.findOne({ _id : "b" }) 
{ "_id" : "b", "path" : "a,b," } 
> t.find({ path : new RegExp("^" + nodeb.path) }) 
{ "_id" : "b", "path" : "a,b," } 
{ "_id" : "c", "path" : "a,b,c," } 
{ "_id" : "d", "path" : "a,b,d," } 
{ "_id" : "g", "path" : "a,b,g," }