我在PostgreSQL的Knex路由上遇到一些问题。我试图插入数据库中,但仅当该项目不在数据库中时才插入。我正在尝试使用不存在的地方,但是它似乎并没有按照我想要的去做。感谢您能给我的任何帮助。
谢谢!
app.post('/addcart', (req,res)=>{
const{customer_id, product_id,item_quantity}=req.body;
db('shopping_carts')
.insert({
customer_id:customer_id,
product_id:product_id,
item_quantity:item_quantity
})
.whereNotExists(db.select('*').from('shopping_carts').where('product_id',product_id))
.then(item=>{
console.log(item)
res.json(item)
})
.catch((err)=>{
if(err.column === 'customer_id'){
res.status(400).json({message:err})
console.log('test')
}else{
res.status(500).json({message:err})
// console.log(err.name);
}
})
})
答案 0 :(得分:1)
您不能将whereNotExists查询与插入查询结合使用,由于其复杂性,他们不支持此查询。因此,在您的方法链中插入后,knex会忽略whereNotExists调用。
您需要先检查是否存在,然后通过单独的调用进行插入。
您还可以编写原始查询。这是一个例子,不是很漂亮: https://github.com/tgriesser/knex/commit/e74f43cfe57ab27b02250948f8706d16c5d821b8
但是,尝试执行此操作时会遇到并发/锁定问题。您最好使用唯一键并让数据库拒绝插入。然后您可以抓住它:
.catch((err) => {
if (err.code === 23505) { res.status(500).json({message: 'duplicate'});
}
编辑,如果您有兴趣,请提供更多信息。这里有一个很长的话题主题: https://github.com/tgriesser/knex/issues/871