2015-02-11 77 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()方法,然后更新(),但它也返回更新的对象。

相关问题