Sequelize how to check if entry exists in database

后端 未结 5 557
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 15:33

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:          


        
相关标签:
5条回答
  • 2021-01-01 16:10

    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
      }
    });
    
    0 讨论(0)
  • 2021-01-01 16:11

    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

    0 讨论(0)
  • 2021-01-01 16:19

    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
      });
    }
    
    0 讨论(0)
  • 2021-01-01 16:20

    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) {
            // ...
        }
    });
    
    0 讨论(0)
  • 2021-01-01 16:24

    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);
    
    0 讨论(0)
提交回复
热议问题