2012-10-07 28 views
2

我使用示例中的方案描述。查找,修改和刪除遞歸嵌入文檔mongoosejs

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," }