2015-02-11 23 views
0

在POST請求來表達我提出以下update到一個數組在我的用戶模式:Mongoose和Express不會反映Schema的更改,直到做出另一個更改?

User.findOne({username: username}, function (err, user) { 
    if (err) { 
     throw err; 
    } 
    if (!user) { 
     res.status(401).send('No user with that username'); 
    } 
    if (typeof items === 'number') { 
     user.update({$push: {cart: items}}, {}, function (err) { 
     if (err) { 
      console.log('There was an error adding the item to the cart'); 
      throw err 
     } else { 
      console.log('update', user); 
      res.send(user); 
     } 
     }); 
    } 
    } 

當我登錄明示用戶,或在我的應用程序,發生的事情是改變我做(在這種情況下,添加到購物車)不會顯示,直到下一次更改。這就好像user在記錄併發送時一樣,沒有更新。我知道在檢查我的數據庫時發生了變化(項目已添加),但在響應中發送的user仍然是原始用戶(來自原始響應)(即變更之前)。如何發送更新後的用戶,我認爲會從user.update返回?

回答

1

要做你想做的事情,會涉及到使用save()方法而不是update(),這涉及到一些不同的實現。這是因爲在模型上調用update()不會修改模型的實例,只會在模型集合上執行更新語句。相反,你應該使用findOneAndUpdate方法:

if (typeof items === 'number') { 
    User.findOneAndUpdate({username: username}, {$push: {cart: items}}, function(err, user){ 
    // this callback contains the the updated user object 

    if (err) { 
     console.log('There was an error adding the item to the cart'); 
     throw err 
    } 
    if (!user) { 
     res.status(401).send('No user with that username'); 
    } else { 
     console.log('update', user); 
     res.send(user); 
    } 
    }) 
} 

它你正在做同樣的事情在幕後,在執行find()方法,然後更新(),但它也返回更新的對象。

相關問題