sorting in mongoose is providing random result

Viewed 20

I have a collection named payments with field named 'sorter' in it, I want to sort my results descending with the 'sorter' field I have no Idea how to do it

return ApiProtectedRoute(
  req,
  res,
  (protectedUserid, protectedUsername, protectedEmail, protectedBalance) => {
    paymentModels
      .find({
        userId: protectedUserid
      }, function(err, payments) {
        if (payments.length == 0) {
          res.status(400).json({
            error: true,
            message: "No payments found",
            info: "getPayments",
          });
        } else if (payments.length > 0) {
          let paymentsWithUsername = [];
          payments.forEach((payment) => {
            userModels.findOne({
              _id: payment.userId
            }, function(err, user) {
              if (err) console.log(err);
              paymentsWithUsername.push({
                ...payment._doc,
                username: user.username,
                email: user.email,
              });
              if (paymentsWithUsername.length === payments.length) {
                res.status(200).json({
                  error: false,
                  payments: paymentsWithUsername,
                  info: "getPayments",
                });
              }
            });
          });
        } else {
          res.status(400).json({
            error: true,
            message: "Something went wrong",
            info: "getPayments",
          });
        }
      })
      .sort({
        sorter: -1
      });
  }
);

this code shows random result at everytime

Payments collection:

payments collection

0 Answers
Related