B
B
BogdanZots2021-10-02 13:35:46
Node.js
BogdanZots, 2021-10-02 13:35:46

How do limit and offset work in node js / sequelize, why doesn't it return what I expect?

Hi everyone , I have 5 items in my database with these fields .

1) id: 13,
      name: 'name1',
     2) id: 103,
      name: 'name2',
     3) id: 105,
      name: 'name3',
     4) id: 113,
      name: 'name4',
     5) id: 115,
      name: 'name5',

I want to get the last 3 elements so I use sequelize limit , offset. In node js I wrote this code
async getAll(req, res) {
    let { limit, page } = req.query;
    limit = 5
    let offset =2
    const targets = await TargetsTasks.findAll({ limit, offset  });
    return res.json(targets.sort((a, b) => a.id - b.id));
  }

But I get
[
    {
        "id": 13,
        "name": "test5112",
    },
    {
        "id": 113,
        "name": "4",
    },
    {
        "id": 115,
        "name": "5",
    }
]

Togezh I get the very first element, 4th and 5th. What am I doing wrong ? Maybe I don't understand something? Help me please!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lorem Ipsum, 2021-10-02
@BogdanZots

example with page & limit:

const page = req.query.page
    const limit = req.query.limit
    const startIndex = (page - 1) * limit
    const endIndex = page * limit
    const data = await db.User.findAll()
    const result = data.slice(startIndex, endIndex)
    res.status(200).json(result)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question