Sequelize how to check if entry exists in database

我怕爱的太早我们不能终老 提交于 2020-11-26 10:52:59

问题


I need to check if entry with specific ID exists in the database using Sequelize in Node.js

  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(isIdUnique(id)){...}

回答1:


Update: see the answer which suggests using findOne() below. I personally prefer; this answer though describes an alternative approach.

You are not returning from the isIdUnique function:

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:


I don't prefer using count to 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?

findOne will get the job done at the first value when there's matching.

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



回答3:


You can count and find.

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

Doc link, v5 Beta Release




回答4:


As Sequelize is designed around promises anyway, alecxe's answer probably makes most sense, but for the sake of offering an alternative, you can also pass in a callback:

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

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



回答5:


I found the answer by @alecxe to be unreliable in some instances, so I tweaked the logic:

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


来源:https://stackoverflow.com/questions/36480587/sequelize-how-to-check-if-entry-exists-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!