我有一个 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.16
和 v5.3.6
之间,其中 v5.3.6
正在工作。
关于mongodb - 为什么 Mongoose 无法在 MongoDB Atlas 中创建索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52665014/