Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize how to check if entry exists in database

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)){...} 
like image 533
mr. Holiday Avatar asked Apr 07 '16 15:04

mr. Holiday


Video Answer


2 Answers

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); 
like image 161
Jalal Avatar answered Sep 20 '22 14:09

Jalal


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) {         // ...     } }); 
like image 22
alecxe Avatar answered Sep 16 '22 14:09

alecxe