Created
March 11, 2021 18:54
-
-
Save whoisryosuke/d1c4b82a95d041161c56641e0c6ef0d1 to your computer and use it in GitHub Desktop.
MongoDB - How to filter a nested object by query params (e.g. metadata object that has different parameters like page)
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
export default async function(req: NextApiRequest, res: NextApiResponse) { | |
const { | |
query | |
} = req | |
const { db } = await connect() | |
// Finds all posts where the `metadata` property is an object | |
// and contains properties like `category`. | |
const posts: Posts[] = await db | |
.collection('posts') | |
.find({ | |
'metadata.dateModified': query.dateModified, | |
'metadata.category': query.category, | |
}) | |
.toArray() | |
// [ { id: 1, name: 'Blog Post', metadata: { dateModified: '2020-02-04', category: 'Uncategorized' } } ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment