Node.js 文本搜索空格转义

Node.js 文本搜索空格转义,node.js,mongodb,mongoose,full-text-indexing,Node.js,Mongodb,Mongoose,Full Text Indexing,我使用nodejsmongoose执行文本搜索 var mongoose = require('mongoose'); var config = require('../config'); var mongoosePaginate = require('mongoose-paginate'); var poiSchema = mongoose.Schema({ city:String, cap:String, country:String, address: S

我使用nodejsmongoose执行文本搜索

var mongoose = require('mongoose');
var config = require('../config');
var mongoosePaginate = require('mongoose-paginate'); 
var poiSchema = mongoose.Schema({
    city:String,
    cap:String,
    country:String,
    address: String,
    description: String,
    latitude: Number,
    longitude: Number,
    title: String,
    url: String,
    images:Array,
    freeText:String,
    owner:String,
});
poiSchema.index({'$**': 'text'});

poiSchema.plugin(mongoosePaginate);
mongoose.Promise = global.Promise;
mongoose.connect(config.database);
module.exports = mongoose.model('Poi', poiSchema);
正如你在这里看到的

poiSchema.index({'$**': 'text'});
我在模式中的每个字段上创建一个文本索引

当我尝试执行文本搜索时,我开发了以下代码:

var term = "a search term";

var query = {'$text':{'$search': term}};
Poi.paginate(query, {}, function(err, pois) {
    if(!pois){
        pois = {
            docs:[],
            total:0
        };
    }
    res.json({search:pois.docs,total:pois.total});
});
不幸的是,当我在术语搜索中使用空格时,它将获取集合中的所有文档,这些文档与按空格分割的术语搜索中的每个字段相匹配

我想象文本索引有一个标记符空格

我需要知道如何避开空白,以便在不拆分整个搜索项的情况下搜索每个字段

我尝试用
\\
替换空白,但没有任何变化


谁能帮帮我吗

MongoDB允许对字符串内容进行文本搜索查询,并支持大小写不敏感、分隔符、停止词和词干分析。默认情况下,搜索字符串中的术语为或。从文档中,
$search
字符串为

MongoDB解析并用于查询文本索引的术语字符串。除非指定为短语,否则MongoDB对术语执行逻辑或搜索

因此,如果
$search
字符串中至少有一个术语匹配,那么MongoDB将返回该文档,MongoDB将使用all术语进行搜索(其中术语是由空格分隔的字符串)

您可以通过指定一个短语来改变这种行为,您可以通过在引号中包含多个术语来改变这种行为。在你的问题中,我认为你想要搜索准确的短语:
一个搜索词
,所以只需将该短语用转义字符串引号括起来即可

以下是一些例子:

  • 鉴于这些文件:

    { "_id" : ..., "name" : "search" }
    { "_id" : ..., "name" : "term" }
    { "_id" : ..., "name" : "a search term" }
    
  • 以下查询将返回

    // returns the third document because that is the only
    // document which contains the phrase: 'a search term'
    db.collection.find({ $text: { $search: "\"a search term\"" } })
    
    // returns all three documents because each document contains
    // at least one of the 3 terms in this search string
    db.collection.find({ $text: { $search: "a search term" } })
    
总之,您可以通过将搜索词集括在转义字符串引号中来“转义空白”。。。使用
“搜索词”而不是
“搜索词”