Skip to content

Instantly share code, notes, and snippets.

@dev0T
Last active February 8, 2023 19:32
Show Gist options
  • Save dev0T/51aa2770b31cd96e95f9d99bbaa7e09d to your computer and use it in GitHub Desktop.
Save dev0T/51aa2770b31cd96e95f9d99bbaa7e09d to your computer and use it in GitHub Desktop.
MongoDB + express.js + Mongoose - Aggregate pipeline instead of populate
const Author = require('../models/author')
const Book = require('../models/book')
//...
const getAll = async ({ author, genre }) => {
let bookAggregate = Book.aggregate()
if (genre) {
bookAggregate = bookAggregate.match({ genres: genre })
}
bookAggregate = bookAggregate
.lookup({
from: Author.collection.name,
as: 'author',
localField: 'author',
foreignField: '_id'
})
.unwind('author')
if (author) {
bookAggregate = bookAggregate.match({ 'author.name': author })
}
return await bookAggregate.exec()
}
// ...
module.exports = {
getAll,
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment