【问题标题】:Sequelize how to check if entry exists in database续集如何检查数据库中是否存在条目
【发布时间】:2016-07-28 14:16:42
【问题描述】:

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

【问题讨论】:

  • 我会使用db.Profile.findOneoptions.rejectOnEmpty 来引发错误,然后将成功回调放在前面的.then 中,并在@987654326 中放置错误cb(未找到等) @

标签: javascript node.js sequelize.js


【解决方案1】:

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

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

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

【讨论】:

  • 如何将 Sequelize 模型加载为 db 对象的子对象?
  • 这段代码到底应该放在哪里?你能分享一个完整的例子吗?
【解决方案2】:

更新:answer which suggests using findOne() below。我个人更喜欢;这个答案虽然描述了另一种方法。

不会从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) {
        // ...
    }
});

【讨论】:

  • 您如何将您的模型关联为主要 sequelize/db 对象的子对象?
  • 使用count表示每次都会遍历数据库中的所有记录。在下面 Jalal 的回答中使用 findOne() 会更有效
【解决方案3】:

你可以数数并找到。

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

Doc 链接,v5 测试版

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

      由于 Sequelize 无论如何都是围绕 Promise 设计的,alecxe's answer 可能最有意义,但为了提供替代方案,您也可以传入回调:

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

      【讨论】:

        【解决方案6】:

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

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-03
          相关资源
          最近更新 更多