我是一名致力于构建电子商务网站的初级程序员,目前我一直在实现我的购物车功能。我使用的堆栈是 NERP 堆栈(Node、Express、React-Redux 和 Postgres)。如果已经存在,我正在尝试更新我的购物车数据库中的项目数量,如果没有,则使用 Sequelize 在我的数据库中创建项目。
//api/cart.js
const router = require('express').Router()
const Cart = require('../db/models/cart')
module.exports = router
router.get('/', (req, res, next) => {
Cart.findAll()
.then(items => res.send(items))
.catch(next)
})
router.put('/', (req, res, next) => {
if(req.body){
Cart.update(req.body, {
where:{
quantity: req.body.quantity++
}})
.then(() => res.sendStatus(204))
.catch(next)
}
else{
Cart.create(req.body)
.then(item => res.send(item))
.catch(next)
}
})
router.delete('/:cartId', (req, res, next) => {
Cart.findOne({
where: { id: req.params.cartId }
})
.then(item => {
item.destroy()
res.send(item)
})
.catch(next);
})
最佳答案
您正在寻找 upsert
:
// create a new row object with the updated values you want
const updatedRow = Object.assign({}, req.body, {
quantity: req.body.quantity++,
});
// "upsert" that new row
Cart.upsert(updatedRow)
.then(() => res.sendStatus(204))
.catch(next)
您可以在 Sequelize documentation 中找到更多信息。
关于node.js - 如何使用 Sequelize 更新我的购物车数据库中的商品数量(如果它已经存在)或如果不存在则创建它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58984090/