2

Good Day,

I am using Sequelize mysql in nodeJs.

My problem is that, given an array of IDs such as [4,5,6,7,8]

And a table T where each row holds a ID. say, Table T:

ID

4

5

7

8

How do I search if all the ID in the array exist in the table?

Do i do a for loop and call find on every loop? Is this done asynchronously or synchronously? How do i wrap it in a promise if i want to do that?

I am not sure what is the proper way for searching if all IDs given an array exist in the table.

Thanks

Ask the cat
  • 47
  • 1
  • 5

3 Answers3

2
SELECT COUNT(DISTINCT id) = 5       -- the values amount in the array
FROM sourcetable
WHERE FIND_IN_SET(id, '4,5,6,7,8')  -- the array as CSV literal

This query will return 1 record with one field. Value 1 means that all array elements are present, 0 - that at least one element is absent.

Array must NOT contain duplicates.

Akina
  • 39,301
  • 5
  • 14
  • 25
1

foreach loop will not work so go with for loop example here following

  const ids =  [4,5,6,7,8];
  for (const id of ids) {
    db.T
      .findOne({
        where: { id: id }
      }).then()
  }
Adeel Nawaz
  • 398
  • 2
  • 10
0

I think you can easily reach this with a findAll or a count. You provide the ids and ask to return them from DB if the number of items match you should be fine

model.findAll({
  where: {
    Id: {
      [Op.or]: [4,5,6,7,8]
    }
  }
});

You can do the same with count if you don't need the objects back

Mirko Urru
  • 25
  • 1
  • 6