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

标签 mongodb mongoose 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 正在工作。

关于mongodb - 为什么 Mongoose 无法在 MongoDB Atlas 中创建索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52665014/

相关文章:

javascript - 无法使用 mongoose 连接到 mongoDB

node.js - 使用 Node.js 20.3.1 连接 MongoDB Atlas 时收到 DEP0170

mongodb - 在 atlas 云中运行的 mango db 上强制关闭连接

node.js - 如何在 Mongoose 中填充多个外键

python - 无法在 Django Rest 框架中创建没有字段的模型

mongodb - AWS + Elastic Beanstalk + MongoDB

javascript - 如何构建我的 nodejs 代码?胖模型/瘦 Controller

Node.js:Mongoose 模式默认随机标记不是随机的

javascript - 如何从一个函数中的多个模式检索和传递数据

mongodb - 如何使用 Robomongo 连接到 MongoDB Atlas?