提问者:小点点

猫鼬不创建索引


我有两个模式-用户&; 会话-在Node/Express/Mongoose项目中。 我在每个模式上都添加了索引。 在我的(免费)Mongo Atlas集群中检查索引时,我可以看到创建了Conversation的索引。 但是,用户不创建所需的索引。

下面是我的用户模式:

null

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);

null

在Mongo Atlas中,用户集合上有两个索引:id(当然)和email。 我从来没有要求给电子邮件做索引。 年龄位置用户名没有索引。 怎么解决这个问题?


共1个答案

匿名用户

由于mongoose文档(https://mongoosejs.com/docs/guide.html#indexes),您可以在模式中的路径级别进行字段级别的索引。 例如,如果需要索引年龄,可以在架构中执行以下操作:

age: { type: String, index: true},

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