These are chat archives for Automattic/mongoose

29th
Oct 2018
Maurizio Bellemo
@mbellemo_twitter
Oct 29 2018 20:06
Hi all. I would kindly ask you for a code review. I just create a simple endpoint that retrieves a list of feedbacks with pagination and search. I am looking for the best practises and I would kindly ask you to dissect the code (it works already. I am just curious about better ways)
router.get('/:id/feedbacks/', authenticate(['user']), (req, res) => {
    const filter = {
        company_id: req.user.company_id,
        project_id: req.params.id
    };
    if (req.query.search) {
        filter.$and = [{ $or: [{ title: { $regex: req.query.search, $options: 'i' } }, 
        { description: { $regex: req.query.search, $options: 'im' } }] }];
    }

    var perPage = 25
    var page = req.query.page || 1

    Feedback.find(filter)
        .skip((perPage * page) - perPage)
        .limit(perPage)
        .then((feedbacks) => {
            Feedback.countDocuments(filter)
                .then((count) => {
                    res.send({
                        feedbacks,
                        current: page,
                        pages: Math.ceil(count / perPage),
                        total: count
                    });
                })
        }, (e) => {
            res.status(400).send(e);
        });
});