簡體   English   中英

如何在 mongoose 中使用多個值對字段應用過濾器

[英]how to apply filter on field using multiple values in mongoose

我有一個 model 包含字段state類型的枚舉並且只接受三個值

active
disabled
deleted

目前正在過濾以獲取所有活動的

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

但我有一個案例,我需要獲得同時聲明activedisabled的帖子,我在 mongoose 文檔中搜索了一些我可以使用的東西,但目前我什么也沒找到,我想要一些干凈的東西來實現這個代碼

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}
const query = { state: { $in: [ "active", "disabled"] } }
const posts = await post.find(query)

這將生成一個帖子列表,其 state 是activedisabled

$in 運算符選擇字段值等於指定數組中的任何值的文檔。 要指定 $in 表達式,請使用以下原型:

來自MongoDB 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM