2016-09-28 108 views
0

Mongo:3.2.1。貓鼬不堅持返回對象

我定義爲這樣一種模式:

var MySchema = new Schema(
    { 
    .... 
    records: {type: Array, "default": []}; 

我第一次創建基於沒有記錄字段模式中的對象和它的正確添加到數據庫中。然後我更新對象作爲這樣:

客戶

angular.extend(this.object.records, [{test: 'test'}]); 
this.Service.update(this.object); 

服務器(省略了無 - 有問題的代碼)

function saveUpdates(updates) { 
    return function(entity) { 
    var updated = _.merge(entity, updates); 
    return updated.save() 
     .then(updated => { 
     console.log(updated); 
     Model.find({_id: updated._id}).then((data)=> console.log(data)); 
     return updated; 
     }); 
    }; 
} 

第一的console.log打印帶有記錄的對象字段已更新。第二個不打印對象。我錯過了什麼?解決的承諾如何與持久對象不同?不應該dataupdated是否相同?

+1

'Object.find'?你的模型被命名爲「對象」,或者我錯過了什麼? –

+0

這不是我在這裏調用它來保持簡單,但我現在意識到我讓它感到困惑。我將編輯 – Mika

+0

您是否嘗試先執行更新,然後從「then」回調中返回找到的對象? –

回答

1

我覺得你有幾個問題。

您正在使用變量'updated'兩次。

var updated = _.merge(entity, updates); // declared here 
return updated.save() 
    .then(updated => { // trying to re-declare here 

另一個問題可能是您試圖將'updates'屬性與mongo對象合併,而不是實際的對象值。嘗試在您的mongo對象上調用.toObject()以獲取數據。

function saveUpdates(updates) { 
    return function(entity) { 
    // call .toObject() to get the data values 
    var entityObject = entity.toObject(); 
    // now merge updates values with the data values 
    var updated = _.merge(entityObject, updates); 
    // use findByIdAndUpdate to update 
    // I added runValidators in case you have any validation you need 
    return Model 
     .findByIdAndUpdate(entity._id, updated, { 
     runValidators: true 
     }) 
     .exec() 
     .then(updatedEntity => { 
     console.log(updatedEntity); 
     Model.find({_id: entity._id}) 
      .then(data => console.log(data)); 
     }); 
    } 
} 
+0

我不認爲第一個是問題,實際上改變變量名不會改變任何內容。使用'findByIdAndUpdate'確實解決了我的問題,實際上我甚至不需要再合併字段。 – Mika