簡體   English   中英

使用 Mongoose 在 Node JS 中進行全文搜索

[英]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);
                }
        });

要使$text查詢工作,MongoDB 需要使用文本索引為字段建立索引。 要通過 mongoose 創建此索引,請使用

fields: {type: [String], text: true}

有關文本索引的 MongoDB 文檔,請參見此處

您需要將文本索引添加到您的架構中,如下所示:

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.

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