![](/img/trans.png)
[英]Push objects from array to mongoose array model field | MongoDB Mongoose
[英]Filtering with an array of objects Regex in mongodb and mongoose
我正在嘗試創建一個可以使用至少 3 個字母實現的dynamic
過濾器。 我有很多字段,我將對其進行過濾。
例如,如果我試圖通過email
查找用戶,我希望能夠輸入“@gma”或至少是“gma”,理想情況下,它應該返回包含指定過濾值的所有用戶的數組。 搜索firstName
等屬性時,這應該是相同的
我當前的解決方案只有在我提供與我的數據庫中已有的值相匹配的完整值時才有效。 例如test@gmail.com
用於email
或john
用於firstName
。 我希望能夠為后者鍵入jo
。
const regexPattern = new RegExp(["^", filterUsersByValue, "$"].join(""), "i");
const filteredU = UserModel.find({ [filterUsersBy]: regexPattern})
如果我理解正確,由於您使用的是 JS,您可以像這樣創建find
對象:
let findObj = {}
findObj[userKey] = {$regex:userFilter, $options:"i"}
const filteredU = UserModel.find(findObj)
這會像這樣創建 que 對象:
const userFilter = "gma" const userKey = "email" let findObj = {} findObj[userKey] = {$regex:userFilter,$options:"i"} console.log(findObj)
與此查詢中的相同的是什么
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.