Search code examples
node.jsmongodbmongooseindexing2dsphere

Define a Mongoose Schema index (2dsphere) on an optional parameter


I have an user model, which can be of two types : postulant and recruiter.

I want the postulants to have a geolocation field, but not the recruiter, and I have to make them in a single Model.

There's a part of my model :

const schema = new mongoose.Schema(
{
    type: {type: String},
    name: {type: String},
    geolocation: {
        name: {type: String},
        type: {type: String, default: 'Point'},
        coordinates: {type: [Number]}
    }
}
)

schema.index({ geolocation: '2dsphere' })
export default mongoose.model('User', schema)

My problem is :

When I try to create a 'recruiter', I have an error saying that Mongo failed to index 'geolocation' into a 2dsphere index. And I understand this problem.

I want to index geolocation only if it's not null, so I can create recruiter without saving their location, and create postulants with their location saved.

Can you help me? :)


Solution

  • I figure what the problem was :

    I defined :

    geolocation: {
            name: {type: String},
            type: {type: String, default: 'Point'},
            coordinates: {type: [Number]}
        }
    

    The fact is that, with the default: 'Point', I had an geolocation object who was created, with an empty array. To solve this, I just removed this default: 'Point' and the object is not created, so the schema.indexis not running.