I have two schemas - User & Conversation - in a node/express/mongoose project. I've added indexes on each schema. When checking the indexes in my (free) Mongo Atlas Cluster, I can see that Conversation's index is created. However, User doesn't create the required indexes.
Here is my 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);
In Mongo Atlas, there are two indexes on the users collection: id (of course), and email. I never asked to index email. age, location, and username are not indexed. How to fix this?
Due to the mongoose documentation (https://mongoosejs.com/docs/guide.html#indexes) you can do the field level indexing within your Schema at the path level. For example if you need to index age, you can do as below within your schema:
age: { type: String, index: true},
You are trying to make a compound index in your code which consists of a 2dsphere index. I guess this is not what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With