Created
November 19, 2018 00:30
-
-
Save MorenoMdz/8b1942e6c23b5fdff0cdd6fa63fffa27 to your computer and use it in GitHub Desktop.
Mongoose JS filter a virtual field by its length
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| exports.getNewProblemsList = async (req, res, next) => { | |
| const page = req.params.page || 1; | |
| const limit = 10; | |
| const skip = page * limit - limit; | |
| const problemPromise = Problem.find() | |
| .populate('author hardware repairsV', 'name') | |
| .skip(skip) | |
| .limit(limit) | |
| .sort({ created: 1 }) | |
| .select({ | |
| photos: 0, | |
| description: 0, | |
| video: 0, | |
| board_model: 0, | |
| }); | |
| const countPromise = Problem.count(); | |
| const [problems, count] = await Promise.all([problemPromise, countPromise]); | |
| const pages = Math.ceil(count / limit); | |
| if (!problems.length && skip) { | |
| req.flash( | |
| 'info', | |
| `You asked for page ${page} that does not exists. Redirecting to the page ${pages}!` | |
| ); | |
| return; | |
| } | |
| // Here lies the problem, when you have a virtual field (here repairsV is virtual to Problem model from Virtual) you have many limitations. | |
| // Before passing it the the view as problemsZero, I filtered out only the problems that have zero repairs linked from the virtual field. | |
| problemsZero = problems.filter(problem => !problem.repairsV.length); | |
| res.locals.newProblemsList = { | |
| problems, | |
| problemsZero, | |
| page, | |
| pages, | |
| count, | |
| }; | |
| next(); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment