Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Mongoose在Node JS中进行全文搜索_Javascript_Node.js_Mongodb_Mongoose_Full Text Search - Fatal编程技术网

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

Javascript 使用Mongoose在Node JS中进行全文搜索,javascript,node.js,mongodb,mongoose,full-text-search,Javascript,Node.js,Mongodb,Mongoose,Full Text Search,我正在尝试对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 } 但是

我正在尝试对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'})
如果您希望包含所有字符串字段

以便
$text
查询正常工作,MongoDB需要使用文本索引对字段进行索引。要通过mongoose创建此索引,请使用

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

对于文本索引的MongoDB文档。

如果出于某种原因,添加测试索引不是一个选项,您也可以在聚合管道中使用运算符来匹配字符串

$regex

为模式匹配字符串提供正则表达式功能 在查询中。
MongoDB使用与Perl兼容的正则表达式(即。 “PCRE”)版本8.42,支持UTF-8

要使用$regex,请使用 以下语法:

{:{$regex:/pattern/,$options:''}
{:{$regex:'pattern',$options:'}
{:{$regex:/pattern/}
在MongoDB中,还可以使用正则表达式对象(即。 /模式/)来指定正则表达式:

{:/pattern/}

您使用的是哪个mogoose版本?当前使用的是Mongoose 4.7.0您需要在字段上创建一个文本索引:
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
{ <field>: /pattern/<options> }