Home > Software engineering >  Error query.skip is not a function when separated from await Order.find({...})
Error query.skip is not a function when separated from await Order.find({...})

Time:07-09

I'm working on a project where I'm trying to paginate orders in order from the most recent to oldest. Before, I added the pagination I had a .sort() that covered this in the frontend, but after adding the pagination it wasn't working properly, so I figured it was best to do this in the backend before any pagination occurred. I'm using .skip() and .limit() to create my pagination. I'm currently, getting an issue stating query.skip is not a function. I've added console.log(query) to check what values the array has, and I get a list of all of the orders in the correct order. When I first added the pagination I had:await Order.find({user:req.user._id}).skip(skip).limit(perPage), which didn't give me any errors, but when I separate .skip() I keep getting the stated error. I'm unsure why I'm getting this error, and I would really appreciate any help or advice on how to fix this. Thank you!

orderRouter.get(
    '/mine',
    isAuth,
    expressAsyncHandler(async (req, res) => {
        const page = parseInt(req.query.page) || 1;
        const perPage = parseInt(req.query.limit) || 20;
        const skip = (page - 1) * perPage;
        let userOrders = await Order.find({ user: req.user._id });
        const query = userOrders.sort((a,b) => new Date(b.createdAt) - new Date(a.createdAt));
        const orders = query.skip(skip).limit(perPage)
        res.status(200).send(orders);
    }),
);

Additional Note:

let userOrders = await Order.find({ user: req.user._id });
const query = userOrders.skip(skip).limit(perPage)

Also, gives an error stating userOrders.skip is not a function

And if I have:

let userOrders = await Order.find({ user: req.user._id }).sort((a,b) => new Date(b.createdAt) - new Date(a.createdAt))

I'm getting an error stating: Invalid sort() argument. Must be a string, object, or array.

CodePudding user response:

You need to not await the query as that would get executed and further chaining would happen on the returned object.

Something like below:

const userOrdersQuery = Order.find({ user: req.user._id });
const userOrders = await userOrdersQuery.skip(skip).limit(perPage);

CodePudding user response:

In case anyone else is having trouble with this, the issue was that .sort() is not a normal javascript .sort(). Instead, .sort() needs to be written for mongodb, since that is the database that I am using and where my documents are coming from. Due to this, in my case, to .sort() for the date a document was created at (createdAt) from newest to oldest would be written like this: .sort({createdAt: -1}).

  • Related