Last active
February 8, 2023 19:32
-
-
Save dev0T/51aa2770b31cd96e95f9d99bbaa7e09d to your computer and use it in GitHub Desktop.
MongoDB + express.js + Mongoose - Aggregate pipeline instead of populate
This file contains 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
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