Javascript Sequelize 如何检查数据库中是否存在条目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36480587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sequelize how to check if entry exists in database
提问by mr. Holiday
I need to check if entry with specific ID exists in the database using Sequelize in Node.js
我需要使用 Node.js 中的 Sequelize 检查数据库中是否存在具有特定 ID 的条目
function isIdUnique (id) {
db.Profile.count({ where: { id: id } })
.then(count => {
if (count != 0) {
return false;
}
return true;
});
}
I call this function in an if statement but the result is always undefined
我在 if 语句中调用此函数,但结果始终未定义
if(isIdUnique(id)){...}
采纳答案by alecxe
You are not returningfrom the isIdUnique
function:
您不是从isIdUnique
函数返回:
function isIdUnique (id) {
return db.Profile.count({ where: { id: id } })
.then(count => {
if (count != 0) {
return false;
}
return true;
});
}
isIdUnique(id).then(isUnique => {
if (isUnique) {
// ...
}
});
回答by Jalal
I don't prefer using countto check for record existence. Suppose you have similarity for hundred in million records why to count them all if you want just to get boolean value, true if exists false if not?
我不喜欢使用计数来检查记录是否存在。假设您有数百万条记录的相似性,如果您只想获得布尔值,为什么要将它们全部计算在内,如果存在则为真,否则为假?
findOnewill get the job done at the first value when there's matching.
findOne将在匹配时在第一个值处完成工作。
const isIdUnique = id =>
db.Profile.findOne({ where: { id} })
.then(token => token !== null)
.then(isUnique => isUnique);
回答by Max Sherbakov
回答by Wayne Smallman
I found the answer by @alecxeto be unreliable in some instances, so I tweaked the logic:
我发现@alecxe 的答案在某些情况下不可靠,所以我调整了逻辑:
function isIdUnique (id, done) {
db.Profile.count({ where: { id: id } })
.then(count => {
return (count > 0) ? true : false
});
}
回答by Drazen Bjelovuk
As Sequelize is designed around promises anyway, alecxe's answerprobably makes most sense, but for the sake of offering an alternative, you can also pass in a callback:
由于 Sequelize 无论如何都是围绕承诺设计的,alecxe 的回答可能最有意义,但为了提供替代方案,您还可以传入回调:
function isIdUnique (id, done) {
db.Profile.count({ where: { id: id } })
.then(count => {
done(count == 0);
});
}
}
isIdUnique(id, function(isUnique) {
if (isUnique) {
// stuff
}
});