javascript - 如何使用 Knex 仅将唯一数据插入 Postgres?

标签 javascript database knex.js

我正在创建一个简单的“出勤”数据库,学生每天只能“签到”一次。每次 checkin 都将包含用户 ID、姓名、时间和日期。使用 Knex,我怎么能只允许每个学生每天签到一次。

我尝试了来自 this thread 的“whereNotExists”的几种变体但似乎没有任何效果。

目前这是我的插入语句:

db('checkins').insert(db
.select(attrs.user_id, attrs.user_name, attrs.date, attrs.created_at)
.whereNotExists(db('checkins').where('user_name', attrs.user_name).andWhere('date', attrs.date).then(() => {
  console.log('successful insert')
}))

然后我收到此错误(“alice_id”是我在“attrs.user_id”中使用的测试值):

Unhandled rejection error: column "alice_id" does not exist

最佳答案

你应该在插入之前验证,即

db('checkins')
.where({
  user_id: attrs.user_id,
  date: attrs.date
})
.first() // getting the first value
.then((found) => {
   if (found){
     res.json('already present');
   }else{
     // now insert data
      db('checkins')
        .insert({
          // your data
        });
   }
});

关于javascript - 如何使用 Knex 仅将唯一数据插入 Postgres?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43443858/

相关文章:

javascript - 无法使用 jquery 发布带有 json 的帖子

javascript - PhantomJS 获取文档元素位置

mysql - 创建优化的mysql数据库

node.js - Knexfile不读取环境变量?

javascript - knex.js 迁移中的时间戳字段

javascript - arc() 函数中的 HTML5 canvas 线条模糊

php - 如何将数组存储在数据库列中

database - 在大型应用程序中使用 Qt 数据库

javascript - 如何在 Objection.js 中定义和使用相关模型

javascript - 在 javascript 对象初始化中使用数字作为属性有什么好处?