我有兩個集合,第一個在第二個集合中具有一個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) {});
});
});
感謝您的幫助
感謝您的示例。我會牢記這一點。異步邏輯是我仍在習慣的思維轉變! – Tom 2012-01-11 05:30:19