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

时间:2016-04-07 15:22:59

标签: javascript node.js sequelize.js

我需要使用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)){...}

6 个答案:

答案 0 :(得分:14)

我不喜欢使用计数来检查记录是否存在。假设你有几百万条记录的相似性,如果你只想获得布尔值,为什么要将它们全部计算,如果不存在,则为真,如果不存在则为真?

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

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

答案 1 :(得分:8)

没有从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) {
        // ...
    }
});

答案 2 :(得分:1)

由于Sequelize是围绕承诺设计的,alecxe's answer可能最有意义,但为了提供替代方案,你也可以传递一个回调:

replace()

答案 3 :(得分:1)

你可以数数和找到。

    Project
  .findAndCountAll({
     where: {
        title: {
          [Op.like]: 'foo%'
        }
     },
     offset: 10,
     limit: 2
  })
  .then(result => {
    console.log(result.count);
    console.log(result.rows);
  });

Doc链接,v5 Beta版

答案 4 :(得分:0)

我发现the answer by @alecxe在某些情况下不可靠,因此我调整了逻辑:

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

答案 5 :(得分:0)

扩展@Jalal 的回答,如果您在保持简单的 Sequelize 结构的同时非常关注性能影响,并且不需要行数据,我建议您只从数据库中请求一列。当您甚至不会使用它们时,为什么要浪费带宽和时间要求数据库返回所有列?

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

attributes 字段告诉 Sequelize 仅从数据库请求 id 列,而不发送整行的内容。

同样,这可能看起来有点过分,但在规模上,如果您有许多包含大量数据的列,这可能会对性能产生巨大影响。