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

Sequelize how to check if entry exists in database

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

更新:。我个人比较喜欢;这个答案虽然描述了另一种方法。

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

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

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

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

由于 Sequelize 是围绕 promises 设计的, 可能最有意义,但为了提供替代方案,您也可以传入回调:

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

isIdUnique(id, function(isUnique) {
  if (isUnique) {
    // stuff
  }
});

你会数数并找到。

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

Doc link,v5 测试版

我发现 在某些情况下不可靠,所以我调整了逻辑:

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

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

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

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

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