Javascript 如何使用Knex将唯一数据插入Postgres?
我正在创建一个简单的“出勤”数据库,学生每天只能“报到”一次。每次签入都将包括用户id、姓名、时间和日期。使用Knex,我怎么能每天只允许每个学生签入一次 我尝试了“whereNotExists”的几种变体,但似乎没有任何效果 目前这是我的insert语句:Javascript 如何使用Knex将唯一数据插入Postgres?,javascript,database,knex.js,Javascript,Database,Knex.js,我正在创建一个简单的“出勤”数据库,学生每天只能“报到”一次。每次签入都将包括用户id、姓名、时间和日期。使用Knex,我怎么能每天只允许每个学生签入一次 我尝试了“whereNotExists”的几种变体,但似乎没有任何效果 目前这是我的insert语句: db('checkins').insert(db .select(attrs.user_id, attrs.user_name, attrs.date, attrs.created_at) .whereNotExists(db('check
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'中使用的测试值):
您应该在插入之前进行验证,即
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
});
}
});
谢谢这是可行的,但我最终改为使用综合指数,这样它就不会在任何比赛条件下失败。如下所示:table.unique(['user\u id','check\u date']);
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
});
}
});