【问题标题】:mongoose index already exists with different options猫鼬索引已经存在不同的选项
【发布时间】:2017-04-30 06:14:10
【问题描述】:

我正在为我的应用程序实现搜索结果视图。 我发现 mongoose 在内部提供了带有 $text 的全文搜索功能。

我把下面的代码放到 Post.js

PostSchema.index({desc: 'text'}); //for example

这是我放在路由文件 route/posts.js 中的代码

Post.find({$text: {$search : 'please work!'}}).exec(function (err, posts) {...}) 

我想出的错误信息如下

Index with pattern: { _fts: "text", _ftsx: 1 } already exists with different options

有没有人知道如何处理这个错误并找出答案? 谢谢你。

【问题讨论】:

    标签: javascript node.js mongodb mongoose full-text-search


    【解决方案1】:

    检查您定义了文本索引的字段。现在 mongodb 每个集合只允许一个文本索引。因此,如果您在 desc 列上定义了文本索引并尝试在其他列上使用该索引,您一定会收到此错误。

    您能否尝试查询您的索引并查看您在哪个列上创建了它。要获取索引,您可以这样做

    db.collection.getIndexes()
    

    它会返回类似这样的东西

    [
        {
            "v" : 1,
            "key" : {
                "_id" : 1
            },
            "name" : "_id_",
            "ns" : "some.ns"
        },
        {
            "v" : 1,
            "key" : {
                "_fts" : "text",
                "_ftsx" : 1
            },
            "name" : "desc_text",
            "ns" : "some.ns",
            "weights" : {
                "title" : 1
            },
            "default_language" : "english",
            "language_override" : "language",
            "textIndexVersion" : 2
        }
    ]
    

    现在如果你想在其他列中也使用这个索引,只需删除这个索引

    db.collection.dropIndex('desc_text');
    

    然后通过包含您希望被文本索引覆盖的所有列来重新创建它,

    db.collection.createIndex({
        title:'text;,
        body: 'text;,
        desc: 'text',
        ...... and so on
    });
    

    【讨论】:

    • 非常感谢您提供清晰快速的解决方案。现在可以了!
    • 在我的例子中,我更改了一个列名,所以我不得不删除并重新创建
    • 当然,如果其中一列定义了索引,则需要重新创建索引。
    猜你喜欢
    • 2019-01-11
    • 2020-06-01
    • 2015-07-25
    • 1970-01-01
    • 2020-10-03
    • 2019-03-19
    • 2021-06-11
    • 2017-03-02
    • 2017-01-26
    相关资源
    最近更新 更多