0

This is my node Api

router.post("/*****", async function(req, res, err) {
  let limit = 5;
  let offset = 0;
  tblAdmin
    .findAndCountAll()
    .then(data => {
      console.log("hello world", req.body);
      let page = (req.body.page && req.body.page) || 1;
      let sortfield = req.body.sortfield;
      let sortOrder = req.body.sortOrder;
      let pages = Math.ceil(data.count / limit);
      offset = limit * (page - 1);
      tblAdmin
        .findAll({
          attributes: ["id", "firstName", "lastName", "status", "email"],
          limit: limit,
          offset: offset
          // order: [`firstName`, `DESC`]
          // $sort: { id: 1 }
        })
        .then(users => {
          res.status(200).json({
            status: 1,
            message: "Data has been retrieved",
            result: users,
            count: data.count,
            pages: pages
          });
        });
      // res.status(200).json({
      //   status: 1,
      //   message: "Data has been retrieved",
      //   data: data.map(result => {
      //     return {
      //       id: result.id,
      //       firstName: result.firstName,
      //       lastName: result.lastName,
      //       status: result.status,
      //       email: result.email
      //     };
      //   })
      // });
    })
    .catch(err => {
      res.status(500).json({
        status: 0,
        message: "Data is not retrieved from database"
      });
    });
});

and this is my react front end

axios.post(`http://abc/**`, params).then(res => {
      const pagination = { ...this.state.pagination };
      let apiData = res.data.result;
      console.log("Data", apiData);
      console.log("params", params);
      if (res.data.status === 1) {
        const objects = apiData.map(row => ({
          key: row.id,
          id: row.id,
          firstName: row.firstName,
          lastName: row.lastName,
          status: row.status,
          email: row.email
        }));
        console.log(res.data);
        pagination.total = res.data.count;
        this.setState({
          loading: false,
          data: objects,
          pagination
        });
      } else {
        console.log("Database status is not 1!");
      }
    });

now this is shown on a table and when i select the field of table in front end it should show ascending or descending order i need to do that order in backend. from front end i m sending param which includes pagination, sortfield and sortorder and i m getting that in backend now what should i do to change the table according to my order?

Kyaw Kyaw Soe
  • 3,258
  • 1
  • 14
  • 25
RsK
  • 15
  • 7
  • What's wrong with order: [sortfield, sortOrder] – Sagar Mar 19 '19 at 04:17
  • @Sagar it gives error. Unhandled rejection TypeError: Cannot read property '_modelAttribute' of undefined at Object.quote (/***/node_modules/sequelize/lib/dialects/abstract/query-generator.js:874:27) at Object.collection.slice.forEach.collectionItem – RsK Mar 19 '19 at 04:26
  • make sure you have value in those two variables – Sagar Mar 19 '19 at 04:46
  • @Sagar this ascending desc is to happen onclick event in front end after i click on the field on table only after that this should happen in backend – RsK Mar 19 '19 at 04:49
  • are you passing pagination information over api? – Sagar Mar 19 '19 at 06:09

1 Answers1

2

The document can be found here

router.post("/*****", async function(req, res, err) {
  let limit = 5;
  let offset = 0;
  tblAdmin
    .findAndCountAll()
    .then(data => {
      console.log("hello world", req.body);
      let page = (req.body.page && req.body.page) || 1;
      let sortfield = req.body.sortfield;
      let sortOrder = req.body.sortOrder;
      let pages = Math.ceil(data.count / limit);
      offset = limit * (page - 1);
      tblAdmin
        .findAll({
          attributes: ["id", "firstName", "lastName", "status", "email"],
          limit: limit,
          offset: offset
          order: [[sortfield || 'id', sortOrder || 'DESC']] // fixed at here
        })
        .then(users => {
          res.status(200).json({
            status: 1,
            message: "Data has been retrieved",
            result: users,
            count: data.count,
            pages: pages
          });
        });
    })
    .catch(err => {
      res.status(500).json({
        status: 0,
        message: "Data is not retrieved from database"
      });
    });
});

Edit 1: Add sort default if sortfield or sortOrder is undefined

Chuong Tran
  • 3,131
  • 17
  • 25
  • this shows this error Unhandled rejection TypeError: Cannot read property '_modelAttribute' of undefined at Object.quote (/***/node_modules/sequelize/lib/dialects/abstract/query-generator.js:852:46) at Object.getQueryOrders (/***/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1740:34) at Object.selectQuery (/home/rohan/Documents/cms/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1183:27) at QueryInterface.select (/***/sequelize/lib/query-interface.js:1105:27) i m not sending any initial value first the value will send afterwards – RsK Mar 19 '19 at 05:13
  • @RsK Issue because sortfield or sortOrder is undefine. Pls add console.log to debug – Chuong Tran Mar 19 '19 at 06:25