在进行另一项更改之前,猫鼬和 Express 不会反映对架构的更改?
Mongoose and Express not reflecting changes to Schema until another change is made?
在 post 表达请求中,我对我的用户模式中的数组进行了以下 update
:
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);
}
});
}
}
当我在 express 或我的应用程序中登录用户时,发生的情况是我所做的更改(在本例中是添加到购物车)在进行下一次更改之前不会显示。就好像 user
在记录和发送时没有更新。我知道在检查我的数据库时进行了更改(添加了项目)但是响应中发送的 user
仍然是原始用户(来自原始响应)(即更改之前)。如何发送我认为会从 user.update
?
返回的更新用户
要完成您想要做的事情,将涉及使用 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(),然后执行 update(),只是它还 returns 更新的对象。
在 post 表达请求中,我对我的用户模式中的数组进行了以下 update
:
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);
}
});
}
}
当我在 express 或我的应用程序中登录用户时,发生的情况是我所做的更改(在本例中是添加到购物车)在进行下一次更改之前不会显示。就好像 user
在记录和发送时没有更新。我知道在检查我的数据库时进行了更改(添加了项目)但是响应中发送的 user
仍然是原始用户(来自原始响应)(即更改之前)。如何发送我认为会从 user.update
?
要完成您想要做的事情,将涉及使用 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(),然后执行 update(),只是它还 returns 更新的对象。