gpt4 book ai didi

javascript - Sequelize 如何检查数据库中是否存在条目

转载 作者:IT老高 更新时间:2023-10-28 23:07:07 26 4
gpt4 key购买 nike

我需要使用 Node.js 中的 Sequelize 检查数据库中是否存在具有特定 ID 的条目

  function isIdUnique (id) {
db.Profile.count({ where: { id: id } })
.then(count => {
if (count != 0) {
return false;
}
return true;
});
}

我在 if 语句中调用此函数,但结果始终未定义

if(isIdUnique(id)){...}

最佳答案

我不喜欢使用 count 来检查记录是否存在。假设您有数亿条记录的相似性,如果您只想获得 bool 值,为什么要全部计算它们,如果存在则为 true,否则为 false?

findOne 将在匹配时以第一个值完成工作。

const isIdUnique = id =>
db.Profile.findOne({ where: { id} })
.then(token => token !== null)
.then(isUnique => isUnique);

关于javascript - Sequelize 如何检查数据库中是否存在条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36480587/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com