首页 > 解决方案 > 猫鼬不创建索引

问题描述

我在 node/express/mongoose 项目中有两个模式 - 用户和对话。我已经在每个模式上添加了索引。在检查我的(免费)Mongo Atlas Cluster 中的索引时,我可以看到 Conversation 的索引已创建。但是,用户不会创建所需的索引。

这是我的用户架构:

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. 我从来没有要求索引电子邮件。age, location, 并且username不被索引。如何解决这个问题?

标签: node.jsmongodbexpressmongoose

解决方案


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

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

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


推荐阅读