2012-08-03 54 views
1

我想通過爲嵌入式文檔創建一個單獨的模型,驗證它,如果驗證成功,將其設置爲主文檔的屬性來僞造非數組嵌套文檔。貓鼬 - 如何將文檔屬性設置爲另一個文檔

在POST/API /文件路徑我做格蘭以下:

var document = new DocumentModel({ 
    title: req.body.title 
}); 

var author = new AuthorModel({ 
    name: req.body.author.name 
}); 

author.validate(function(err) { 
    if (!err) { 
    document.author = author.toObject(); 
    } else { 
    return res.send(err, 400); 
    } 
}); 

console.log(document); 

但它似乎沒有工作 - 控制檯打印出的文檔未經作者。我可能錯過了一些非常明顯的東西,也許我需要做一些嵌套的回調,或者我需要使用一個特殊的setter方法,比如document.set('author',author.toObject())...但是我現在無法自己想象。

回答

0

看起來答案是使用回調來設置document.author並在Schema中定義作者。

像@JohnnyHK指出的,我無法使用原始代碼將文檔記錄到控制檯,因爲author.validate是異步的。因此,解決方案是或者包裝console.log(並可能進一步document.save()在回調author.validate()

這似乎是Mongoose不「設置」模型的任何屬性。沒有在架構中定義由於我的作者是一個對象,我不得不設置的作者字段中的Schema,混合,這樣

下面的代碼工作:

var DocumentModel = new Schema({ 
    title: { type: String, required: true }, 
    author: {}  
}); 
var AuthorModel = new Schema({ 
    name: { type: String, required: true } 
}); 
app.post("/api/documents", function(req, res) { 
    var document = new DocumentModel({ 
     title: req.body.title 
    }); 
    var author = new AuthorModek({ 
     title: req.body.author.name 
    }); 
    author.validate(function(err) { 
     if (!err) { 
      document.author = author; 
      docment.save(function(err) { 
       ... 
      }); 
     } else { 
      return res.send(err, 400); 
     } 
    }) 
}); 
0

看起來像author.validate是異步的,因此您的console.log(document);語句在執行document.author的回調之前執行。您需要將取決於document.author的處理置於回調中。

+0

有沒有一種辦法做沒有嵌套回調?中間件也許? – ragulka 2012-08-03 12:57:33

+0

是的,我認爲使用Mongoose中間件將是一個很好的方式去這裏。 – JohnnyHK 2012-08-03 13:02:35

+0

嗯,它似乎即使我可以'console.log(document.author)'使用回調時,似乎'console.log(文檔)'不包括作者...... – ragulka 2012-08-03 19:18:25