2014-10-17 92 views
1

我有一個貓鼬的模式,看起來像這樣:將字段添加到模型,從貓鼬模式派生

ManifestSchema = new Schema({ 
entries: [{ 
      order_id: String, 
      line_item: {}, // <-- resolved at run time 
      address: {},// <-- resolved at run time 
      added_at: Number, 
      stop: Number, 

     }] 

}, {collection: 'manifests', strict: true }); 

和地方在我有這樣的代碼:

Q.ninvoke(Manifests.findById(req.params.id), 'exec') 
.then(function(manifest) 
{ 
// ... so many things, like resolving the address and the item information 
entry.line_item = item; 
entry.address = order.delivery.address; 
}) 

,我所面臨的問題是沒有在模式中定義地址和line_item,當我在運行時解決它們時,它們不會返回給用戶,因爲它們不在模式中......所以我添加了它們......這導致我另一個不需要的行爲:當我將對象保存回來時,地址和line_item都與清單對象一起保存,我想避免的事情。

有沒有辦法在運行時爲模式添加字段,但是,還沒有在回程中保存它們?

我試圖在貓鼬中使用'虛擬',但他們確實提供我需要的東西,因爲我不是從模式創建模型,而是從數據庫返回。您manifest貓鼬實例

+0

大問題。 – 2015-04-15 06:27:38

回答

4

呼叫toObject()創建JavaScript複製,您可以添加額外的字段爲用戶應答,而不影響您需要保存文檔平地

Q.ninvoke(Manifests.findById(req.params.id), 'exec') 
.then(function(manifest) 
{ 
    var manifestResponse = manifest.toObject(); 

    // ... so many things, like resolving the address and the item information 
    entry.line_item = item; 
    entry.address = order.delivery.address; 
}) 
+0

奇妙的想法!謝謝! – 2014-10-20 15:29:03

+0

非常感謝!你知道這個原因的細節嗎?從貓鼬中返回的實體與「純javascript」對象有什麼不同? – 2015-04-15 06:27:12

+1

@DanielFlippance一個關鍵的區別是Mongoose文檔的屬性是使用['Object.defineProperty']定義的(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/ defineProperty)。 – JohnnyHK 2015-04-15 13:30:58