V
V
Vlad Timofeev2015-01-13 01:34:45
Node.js
Vlad Timofeev, 2015-01-13 01:34:45

How to make express-paginate sort mongoDB model in reverse order, by model field "idNum"?

And again, good time of the day_)
There is a user model in which everyone has an idNum, which is assigned to him during authorization.
According to the express-paginate docks, it seems that you need to go to " localhost:8080/users?page=1&limit=10&idNum=-1 ", but it still doesn't sort users, as they were - they still are.
Maybe you can specify sorting right here (below the code)?

app.get('/users', function (req, res) {
    User.paginate({}, req.query.page, req.query.limit, function(err, pageCount, users, itemCount) {

    		if (err) return next(err);

    		res.format({
        html: function() {
        			res.render('users', {
        				query: req.query,
        				page: 'users',
        				user: req.user,
        				users: users,
        				pageCount: pageCount,
    				   	itemCount: itemCount,
    			    });
    	  		},
    	  		json: function() {
    	  		  // inspired by Stripe's API response for list objects
    				res.json({
          			object: 'list',
    			    	has_more: paginate.hasNextPages(req)(pageCount),
        				data: users
      				});
     		 	}
      	});
    });
  });

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vlad Timofeev, 2015-01-13
@PyTiMa

Heh) and here is the solution: https://github.com/edwardhotchkiss/mongoose-paginate
It was not described in the express-paginate docs that:

/*
 * advanced example usage of `mongoose-pagination`
 * querying for `{ columns: 'title', { populate: 'some_ref' }, { sortBy : { title : -1 } }` items in `MyModel`
 * paginating by second page, 10 items per page (10 results, page 2)
 */

var mongoosePaginate = require('mongoose-paginate');

MyModel.plugin(mongoosePaginate)

MyModel.paginate({}, 2, 10, function(error, pageCount, paginatedResults, itemCount) {
  if (error) {
    console.error(error);
  } else {
    console.log('Pages:', pageCount);
    console.log(paginatedResults);
  }
}, { columns: 'title', populate: 'some_ref', sortBy : { title : -1 }); //Вот и оно!)

And using express-paginate - works too

A
Alexander Aksentiev, 2015-01-13
@Sanasol

First you need to specify by which field to sort at all probably
&sort=idNum&idNum=-1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question