[英]Full-Text Search in Node JS with Mongoose
我正在嘗試對 Mongoose 中的字符串數組執行全文搜索,但出現此錯誤:
{ [MongoError: text index required for $text query]
name: 'MongoError',
message: 'text index required for $text query',
waitedMS: 0,
ok: 0,
errmsg: 'text index required for $text query',
code: 27 }
但是,我確實在用戶架構的字段上聲明了一個文本索引,並且我確認已創建文本索引,因為我使用的是 mLab。 我正在嘗試對字段執行全文搜索
這是我的用戶架構:
var userSchema = mongoose.Schema({
local: {
firstName: String,
lastName: String,
username: String,
password: String,
fields: {type: [String], index: true}
}
});
這是我的全文搜索代碼:
User.find({$text: {$search: search}}, function (err, results) {
if (err) {
console.log(err);
} else {
console.log(results);
}
});
您需要將文本索引添加到您的架構中,如下所示:
userSchema.index({fields: 'text'});
或者使用userSchema.index({'$**': 'text'});
如果要包含所有字符串字段
如果由於某種原因不能選擇添加測試索引,您還可以在聚合管道中使用正則表達式運算符來匹配字符串。
$正則表達式
為查詢中的模式匹配字符串提供正則表達式功能。
MongoDB 使用支持 UTF-8 的 Perl 兼容正則表達式(即“PCRE”)版本 8.42。要使用 $regex,請使用以下語法之一:
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
在 MongoDB 中,您還可以使用正則表達式對象(即 /pattern/)來指定正則表達式:
{ <field>: /pattern/<options> }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.