These are chat archives for Automattic/mongoose

24th
Sep 2018
Faran Ali
@Faran52_twitter
Sep 24 2018 04:27
@lineus thanks man I've got it
Maurizio Bellemo
@mbellemo_twitter
Sep 24 2018 18:39

I am trying to create an endpoint that retrieves a list of customers, and I would like to sort it for two dimensions: value, and then alphabetically.

router.get('/', authenticate(['user']), (req, res) => {
    var perPage = 25
    var page = req.query.page || 1

    var sort = (req.query.sort &&
        _.indexOf(['-name',
            '-size',
            'size',
            '-real',
            'real',
            '-potential',
            'potential'],
            _.trim(req.query.sort)) != -1) ? _.trim(req.query.sort) : 'name';

    Customer
        .find({
            company_id: req.user.company_id
        })
        .skip((perPage * page) - perPage)
        .limit(perPage)
        .sort(sort)
        .then((customers) => {
            Customer.countDocuments().then((count) => {
                res.send({
                    customers,
                    current: page,
                    pages: Math.ceil(count / perPage),
                    total: count
                });
            })
        }, (e) => {
            res.status(400).send(e);
        });
});

I am trying to use the notation with the query builder and string with '-'. With one sorting element works like a charm... with two does not. Any suggestions?