定义一个Mongoose模式索引(2dsphere)在一个可选参数上。

huangapple go评论58阅读模式
英文:

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

问题

我有一个用户模型,它可以分为两种类型:求职者和招聘者。

我想要求职者拥有一个地理位置字段,而招聘者不拥有,我必须将它们放在同一个模型中。

我的模型的一部分如下所示:

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)

我的问题是:

当我尝试创建一个“招聘者”时,我会收到一个错误消息,说Mongo无法将“geolocation”索引为2dsphere索引。我理解了这个问题。

我想要仅在“geolocation”字段不为空时才对其进行索引,这样我就可以创建招聘者而不保存其位置,并创建已保存其位置的求职者。

你能帮助我吗? 定义一个Mongoose模式索引(2dsphere)在一个可选参数上。

英文:

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? 定义一个Mongoose模式索引(2dsphere)在一个可选参数上。

答案1

得分: 0

我明白问题出在哪里:

我定义了:

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

事实是,使用了 default: 'Point',我创建了一个带有空数组的地理位置对象。
为了解决这个问题,我只需移除 default: 'Point',对象就不会被创建,因此 schema.index 也不会运行。

英文:

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.

huangapple
  • 本文由 发表于 2023年1月9日 20:57:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75057579.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定