2012-01-09 19 views
0

我有兩個集合,第一個在第二個集合中具有一個id引用文檔數組。當在貓鼬中避免保存時,可以使用多層嵌套的回調函數嗎?

有一種情況我想創建一個新的DocumentType一個特別的地方,然後一個新的Document引用了DocumentType最後更新原始DocumentType以引用新Document

A DocumentType可以有很多Documents,但Document只能有一個DocumentType。我希望在兩個地方都有參考的原因是爲了稍後簡化更復雜的查詢。

我的問題是:是否有更好的方式來使用貓鼬編寫它,而不是使用這些多個嵌套的回調函數。

我已經放在一起一個簡單的例子來演示。真實情況中有更多的數據,因此我不希望將Document嵌入到DocumentType中,反之亦然。

var DocumentTypeSchema = new Schema({ 
    name: String 
    , desc: String 
    , documents: [{type: Schema.ObjectId, ref: 'Document'}] 
    , ... 
}); 

var DocumentSchema = new Schema({ 
    title: String 
    , doctype: {type: Schema.ObjectId, ref: 'DocumentType'} 
    , ... 
}); 

var Document = mongoose.model('Document', DocumentSchema); 
var DocumentType = mongoose.model('DocumentType', DocumentTypeSchema); 

// Begin the nested callbacks 
// Create a document type 
var type = new DocumentType({...}); 

// Save document type 
type.save(function(err) { 

    // Create new document 
    var document = new Document({ 
     doctype: type.id 
    , ... 
    }); 

    // Save document 
    document.save(function(err) { 

    // Update document type 
    DocumentType.update({_id: document.doctype}, {'$addToSet': {documents: document.id}}, function(err) {}); 
    }); 
}); 

感謝您的幫助

回答

1

我要說的是,通常存在不支持同步處理的更好的方法。 Jani提到的async函數庫的series函數是一個很好的方法來平滑這一點,但我認爲堅持回調結構通常是一個好主意 - 它使得範圍清晰並減少外部依賴 - 除非嵌套得到是荒謬的,或者你需要異步。你的嵌套不是荒謬的,但你可能會考慮async.parallel前進。如果您要創建兩個新實例並在兩者之間保存屬性,則沒有理由同步進行創建。取而代之的是,這樣的事情:

async.parallel({ 
     type: function(callback) { 
      var type = new DocumentType({...}); 
      type.save(function(err) {callback(null, type)}); 
     }, 
     document: function(callback) { 
      var document = new Document({...}); 
      document.save(function(err) {callback(null, document)}); 
     } 
    }, 
    function(err, results) { 
     results.document.doctype = results.type.id; 
     results.document.save(); 
     DocumentType.update(
      {_id: results.type}, 
      {'$addToSet': {documents: results.document.id}}, 
      function(err) {} 
     ); 
    }); 

它需要一個額外的保存,並坦率地說可能是傻這麼小的性能開銷這樣的任務,但它說明了異步處理和良好做法異步的多功能性圖書館。

+0

感謝您的示例。我會牢記這一點。異步邏輯是我仍在習慣的思維轉變! – Tom 2012-01-11 05:30:19

1

您可以使用類似的節點異步的series功能後,對方跑各回調。這樣你就不必將它們嵌套在一起。

https://github.com/caolan/async

+0

感謝您的鏈接。我肯定會在更復雜的情況下使用它 – Tom 2012-01-11 05:28:25