为什么 Mongoose 无法在 MongoDB Atlas 中创建索引?

Why Mongoose cant create an index in MongoDB Atlas?

我有一个 Mongoose 模式,其中包含一个具有特定索引的字段:

const reportSchema = new mongoose.Schema({
    coords: {
    type: [Number],
    required: true,
    index: '2dsphere'
    },
…
}

它在我的本地机器上运行良好,所以当我通过 shell 连接到 MongoDB 时,我得到 db.reports.getIndexes() 的输出:

[
{
    "v" : 2,
    "key" : {
        "_id" : 1
    },
    "name" : "_id_",
    "ns" : "weatherApp.reports"
},
{
    "v" : 2,
    "key" : {
        "coords" : "2dsphere"
    },
    "name" : "coords_2dsphere",
    "ns" : "weatherApp.reports",
    "background" : true,
    "2dsphereIndexVersion" : 3
}
]

然后我将这个应用程序部署到 Heroku 并连接到 MongoDB Atlas 而不是我的本地数据库。它适用于保存和检索数据,但没有创建索引(只有默认索引):

[
{
    "v" : 2,
    "key" : {
        "_id" : 1
    },
    "name" : "_id_",
    "ns" : "weatherApp.reports"
}
]

什么可能导致这个问题? Atlas 允许通过 Web GUI 创建索引,它工作得很好,就像从 shell 创建索引一样。但是 Mongoose 由于某种原因未能执行此操作。

我在使用 mongoose 版本 v5.0.16 时遇到了同样的问题。但是,自从我更新到 v5.3.6,它现在正在 Mongo Atlas 上为我创建(复合)索引。 (我刚刚编写了一个包含两个版本的示例应用程序来验证情况是否如此)。

我不确定哪个版本解决了这个问题,但它介于 v5.0.16v5.3.6 之间,其中 v5.3.6 有效。