node.js - 如何使用 Sequelize 更新我的购物车数据库中的商品数量(如果它已经存在)或如果不存在则创建它?

标签 node.js postgresql express sequelize.js

我是一名致力于构建电子商务网站的初级程序员,目前我一直在实现我的购物车功能。我使用的堆栈是 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/

相关文章:

javascript - 使用 Express JS 阻止来自客户端的不需要的请求

javascript - 如何使用nodejs Zeromq库设置双向消息 channel ?

postgresql - pandas to_sql 中 ' unexpected keyword argument ' fetch' ' 错误的来源?

javascript - 在快速应用程序中调试内存泄漏

javascript - 如何使用express和node进行异步调用

javascript - eval() 处理对象时出现语法错误

mysql - 表 '[database-name].sessions' 不存在 - 使用快速 session

PostgreSQL:设置一列,其中行的序号通过另一个字段排序

postgresql - 使用 PSQL 命令查找主机名和端口

node.js - Node 异步执行