简体   繁体   中英

How to correctly get paginated results in Sequelize using offset?

I have the following simple piece of code:

const users = await User.findAll({
    limit: 10,
    offset: (page - 1) * 10,
    order: [['createdAt', 'DESC']],
    where: { isAdmin: false },
  })

I expect this code to return a paginated user result based on the page . For example, for page = 1 I expect to get the first 10 users, and for page = 2 I expect to get the next 10 users.

In my tests, I'm using bulkCreate to create users:

await models.User.bulkCreate(
        Array.from({ length: 25 }).map((_, i) => ({
          email: `user-${i}@test.com`,
          name: 'test',
          password: 'password1',
        })),
      )

I then make a query with page = 1 , which works as expected - it returns to me user-0@test.com up to user-9@test.com .

However, when I make a query with page = 2 , it returns user-9 up to user-18 . I expect to get user-10 up to user-19 , but instead I get user-9 which I've already received in my first query.

What am I doing wrong here? Thanks in advance.

I think I figured out the problem after playing around with it for the last 40 minutes.

I looked at my Users table and realized that bulkCreate actually creates all of them at the exact same time (which makes sense). That means their createdAt was exactly the same, so my results were not really sorted reliably.

I opted to not use bulkCreate, and instead add a small delay before creating each user, using this somewhat sloppy implementation:

await Promise.all(
    Array.from({ length: 25 }).map(
      (_, i) =>
        new Promise(resolve => {
          setTimeout(async () => {
            await User.create({
              email: `user-${i}@test.com`,
              name: 'test',
              password: 'password1',
            })
            resolve()
          }, i * 50)
        }),
    ),
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM