Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Created March 11, 2021 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whoisryosuke/d1c4b82a95d041161c56641e0c6ef0d1 to your computer and use it in GitHub Desktop.
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)
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