Home > Software design >  how to apply filter on field using multiple values in mongoose
how to apply filter on field using multiple values in mongoose

Time:04-01

i have a model that contain field state type of enum and accept only three values

active
disabled
deleted

and currently am filtering to get all the active ones by

const query = {state : "active" ... other filters here}
const posts = await post.find(query)

but I have a case where I need to get the posts that have stated both active and disabled and I searched in mongoose docs for something I can use but I find nothing at the moment i want something clean that achieve this code

const query1 = {state : "active" ... other filters here}
const posts1 = await post.find(query1)

const query2 = {state : "disabled" ... other filters here}
const posts2 = await post.find(query2)

const posts = {...posts1, ...posts2}

CodePudding user response:

const query = { state: { $in: [ "active", "disabled"] } }
const posts = await post.find(query)

This will result in a list of posts whose state is either active or disabled.

The $in operator selects the documents where the value of a field equals any value in the specified array. To specify an $in expression, use the following prototype:

From MongoDB docs.

  • Related