I’m working on my first project using MongoDB and Mongoose, and I’m having trouble creating a 2dsphere index on a location field in my schema. I’ve been trying to resolve this for over 24 hours, but nothing seems to work.
I have a Mongoose schema where I’m trying to create a 2dsphere index on a location field, which is intended to store GeoJSON data for geospatial queries. Here’s my schema:
code
const adSchema = new Schema<Ad>({
title: { type: String, required: true },
price: { type: Number, required: true },
category: { type: String, required: true },
description: { type: String, required: true },
contact: { type: String, required: true },
files: [{ type: Object, required: true }],
location: {
type: {
type: String,
enum: ['Point'],
required: true
},
coordinates: {
type: [Number],
required: true
}
},
userEmail: { type: String, required: true }
}, {
timestamps: true,
});
// Correct 2dsphere index
adSchema.index({ location: '2dsphere' });
export const AdModel = (models?.Ad as Model) || model(‘Ad’, adSchema)
The Issue:
Index Not Being Created: Despite having the index defined correctly as adSchema.index({ location: ‘2dsphere’ });, the location_2dsphere index is not created. However, if I define the index on a different field name, such as Location or llocation, it creates the index with no issues.
Case Sensitivity: I’ve ensured that the field name location is consistently lowercase across the schema and index definition, but this doesn’t resolve the issue.
I expect that the 2dsphere index should be created on the location field as location_2dsphere, allowing me to perform geospatial queries on the data.
1