Mongoose无法创建索引。

3

我有两个模式 - User 和 Conversation,这是一个基于 node/express/mongoose 的项目。我已经在每个模式上添加了索引。当我在我的(免费的)Mongo Atlas集群中检查索引时,我可以看到Conversation的索引已经创建。然而,User没有创建所需的索引。

这是我的User Schema:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema(
  {
    username: { type: String, required: true, unique: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    age: { type: String},
    location: {
      type: { type: String, enum: ["Point"], default: "Point" },
      coordinates: { type: [Number], default: [0, 0] },
    },
  },
  { timestamps: true }
);


userSchema.index({ age: 1, location: "2dsphere", username: 1 });

module.exports = mongoose.model("User", userSchema);

在Mongo Atlas中,用户集合上有两个索引:id(当然),和email。我从未要求对email进行索引。agelocationusername没有被索引。如何解决这个问题?

不要依赖mongoose来创建索引,最好手动创建它们。 - SuleymanSah
在一个Express/Mongoose项目中,如何手动创建索引?我只有一个mongoose.connect函数和一些模式。我应该在哪里实例化它们? - DoneDeal0
在 mongoshell 中使用 https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/ - SuleymanSah
1个回答

2
根据 Mongoose 文档 (https://mongoosejs.com/docs/guide.html#indexes),您可以在 Schema 的路径级别上进行字段级索引。例如,如果您需要对年龄进行索引,可以在您的 schema 中按如下方式操作:
age: { type: String, index: true},

您正在尝试在代码中创建一个由2dsphere索引组成的复合索引。我猜这不是您想要的。

所以我已经在字段级别添加了索引,但仍然不起作用。在检查我的Atlas集群时,唯一的索引是id和email,尽管我请求了年龄,位置和用户名。我已经写了:age: { type: Number, default: null, index: true }, location: { type: { type: String, enum: ["Point"], default: "Point" }, coordinates: { type: [Number], default: [0, 0], index: "2dsphere" }, }。我真的不明白为什么没有创建索引。 - DoneDeal0
我测试了一下,结果很好,所有的索引都已经被创建了,由于你使用了唯一属性,邮件也被索引了。模式没有问题,我猜你应该在其他地方寻找问题。 - Ana Lava
2
好的,我已经让它工作了,但我不知道为什么。我在脚本中写入了 User.ensureIndexes(function (err) { if (err) return handleError(err); }); ,然后就可以了。真是鬼了。 - DoneDeal0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接