Sequelize how to check if a record exists in a database

I need to check if a record with a specific identifier 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)){...}
+4
source share
3 answers

You are not returning from a 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) {
        // ...
    }
});
+7
source

I do not prefer to use count to check for the existence of a record. Suppose you have a similarity for hundreds of millions of records, why count them if you just want to get a boolean, true if false exists, if not?

findOne , .

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

Since Sequelize is designed around promises, alecxe answer probably makes sense, but in order to offer an alternative, you can also pass a callback

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

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

All Articles