修复在MongoDB中删除多个索引时“索引名称必须是字符串”
发布于
如果在MongoDB中删除多个索引时遇到“索引名称必须是字符串”错误,可能是因为您传递的是规范文档而不是名称。
使用方法或命令删除多个索引时,需要在数组中传递索引_名称_(而不是规范文档)。[dropIndexes()](https://database.guide/mongodb-dropindexes/ "MongoDB dropIndexes()")``[dropIndexes](https://database.guide/mongodb-dropindexes-command/ "MongoDB dropIndexes Command")
示例索引
假设我们有以下索引:
db.posts.getIndexes()
输出:
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"title" : 1
},
"name" : "title_1"
},
{
"v" : 2,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "body_text",
"weights" : {
"body" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 3
}
]问题代码
下面是导致此错误的代码示例:
db.posts.dropIndexes( [
{ "_fts" : "text", "_ftsx" : 1 },
{ "title" : 1 }
] )
输出:
uncaught exception: Error: error dropping indexes : {
"ok" : 0,
"errmsg" : "dropIndexes krankykranes.posts (f9083c2c-8291-49d1-95f7-40711186db98) failed to drop multiple indexes [ { _fts: \"text\", _ftsx: 1.0 }, { title: 1.0 } ]: index name must be a string",
"code" : 14,
"codeName" : "TypeMismatch"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DBCollection.prototype.dropIndexes@src/mongo/shell/collection.js:692:11
@(shell):1:1在此示例中,我尝试通过传递其规范文档来删除两个索引,但出现错误。我需要传递索引名称。
溶液
要解决此问题,我只需要传递索引名称而不是它们的规范文档:
db.posts.dropIndexes( [
"body_text",
"title_1"
] )
输出:
{ "nIndexesWas" : 3, "ok" : 1 }这告诉我们索引已成功删除。
检查结果
我们可以再次运行以验证索引是否不再存在。[getIndexes()](https://database.guide/get-a-list-of-indexes-in-mongodb/ "Get a List of Indexes in MongoDB")
db.posts.getIndexes()
输出:
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]两个索引都已按预期删除。