PCG
PCG

Reputation: 2299

How do I sort records from Sequelize?

I have the following API with Sequelize data query.

This works fine but I need to sort the records in decremental order of 'id' in model BuyerAddressBooks. So I used 'order' but it does not have any impact on output. It's always in incremental order. HOw could I modify this? I am new to Sequelize.

{ model: BuyerAddressBooks, attributes: { exclude: commonExcludes },  order: [['id', 'DESC']] },

Here is my API code :

export const PG_getUserDetails = createContract("Any name as of now")  //PG_BuyerProfile#get
  .params("userId")
  .schema({
    userId: V.number(),
  })
  .fn(async (userId) => {
    const user = await User.findByPk(userId, {
      attributes: { exclude: commonExcludes },
      include: [
        { model: PG_UserDetails, attributes: { exclude: commonExcludes } },
        {
          model: BuyerProfile,
          attributes: { exclude: commonExcludes },
          include: {
            model: PhoneNumbers,
            attributes: ["id", "number", "mobileVerified"],
          },
        },
        { model: BuyerAddressBooks, attributes: { exclude: commonExcludes },  order: [['id', 'DESC']] },
      ],      
    }).then(toPlain);
    if (!user) {
      throw new LogError("Profile not found", 400);
    }
    const { buyerProfile, buyerAddressBooks, phoneNumbers } = user;
    const email = R.pathOr(user, ["userDetail", "email"], null);
    return { email, ...buyerProfile, buyerAddressBooks, phoneNumbers };
  })
  .express({
    method: "get",
    path: "/buyer/pg_profile",
    auth: true,
    async handler(req, res) {
      // @ts-ignore
      const user = req.user;
      console.log(`From console : ${user.id}`);
      res.json(await PG_getUserDetails(+user.id));
    },
  }); 

Upvotes: 0

Views: 255

Answers (1)

Anatoly
Anatoly

Reputation: 22783

include option does not have order prop. You can try to indicate order among options for the User model like this:

await User.findByPk(userId, {
      attributes: { exclude: commonExcludes },
      order: [['BuyerAddressBooks', 'id', 'DESC']],
      ...

Upvotes: 1

Related Questions