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)){...}
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);
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) { // ... } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With