我正在嘗試添加用戶用戶名的關鍵字,以便使用 websocket 事件進行更快的查詢。
在我的 userSchema 中,我將關鍵字索引設定為 true:
keywords: {
// for live search of username
type: [String],
index: true,
},
例如,如果用戶的用戶名是“johnsmith”,我需要使用以下內容保存陣列。
user.keywords = [j, jo, joh, john, johns, johnsm, johnsmi, johnsmit, johnsmith]
我將在我的 userSchema.pre('save') 中執行此操作。
下面是我要做什么,但我將如何將用戶名附加到部件陣列,然后設定 user.keywords = 部件?我是否正確索引 user.keywords 屬性?
謝謝!
userSchema.pre(`save`, async function (next) {
const user = this
if (user.isModified(`username`)) {
let parts = []
for (let i = 0; i < user.username.length; i ) {
parts.push(*???*)
}
user.keywords = parts
}
next()
})
uj5u.com熱心網友回復:
正如我所看到的,您試圖確保即使搜索了名稱的一部分,在從資料庫中獲取時也能找到它?
您可以只使用正則運算式進行搜索,而不是將可能的請求寫入陣列。
User.find({ username: {$regex : `/^${requestedSearch}/`}});
現在,這將找到用戶名以請求的字串開頭的結果。
如果您的用戶名是“Steve”并且您搜索“Ste”,它將從資料庫中回傳該用戶。您還可以添加區分大小寫等選項。
以下是更多資訊:https : //docs.mongodb.com/manual/reference/operator/query/regex/
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/376546.html
標籤:javascript 猫鼬 猫鼬模式
