【发布时间】:2019-07-11 07:39:54
【问题描述】:
我的数据库模型中有三个文档模式:pointSchema(只是一个 GeoJSON 点定义)、PlaceSchema(这是一个真实的地方,就像一个夜总会)和 EventSchema(这将存储与派对和节日等事件相关的数据)。
但是我遇到了一些问题。我需要根据他的位置查询事件文档,但是,该位置数据存储在与事件有关系的子文档中。
以下是我的架构定义:
const pointSchema = new mongoose.Schema({
type: {
type: String,
enum: ['Point'],
required: true
},
coordinates: {
type: [Number],
required: true
}
});
const PlaceSchema = new mongoose.Schema(
{
name: {
type: String,
required: true
},
location: {
type: pointSchema,
required: true
}
},
{
versionKey: false,
timestamps: true
}
);
PlaceSchema.index({
name: 'text',
location: "2dsphere"
});
const EventSchema = new mongoose.Schema(
{
name: {
type: String,
required: true
},
place: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'Place'
}
},
{
versionKey: false,
timestamps: true
}
)
EventSchema.index({
name: 'text'
})
我可以使用以下方式过滤 Places 文档:
db.Places.find({
location: {
$geoWithin: {
$centerSphere: [
[ -28.824342, -49.218433 ],
100 / 6378.1
]
}
}
})
但是当我尝试过滤事件时,我不能这样做。我已经尝试过这样的查询:
db.Events.find({
"place.location": {
$geoWithin: {
$centerSphere: [
[ -28.824342, -49.218433 ],
100 / 6378.1
]
}
}
})
但该解决方案不起作用。有人可以帮助我吗?
谢谢。
【问题讨论】:
-
您的
location密钥存在于适当的架构中,您刚刚在事件中引用了它。 -
你好 Anthony,当然...但是我不能在我的事件过滤器中使用那个键(在嵌套文档中)?
-
请说明您需要什么?你需要什么输出,因为你在这里走错了方向。您正在尝试使用引用键访问子/父字段。
-
事件文档中的
place只是一个ObjectId还是作为子文档添加的地方文档本身? -
你好@AbdelrahmanHossam,这个地方只是事件文档中的一个objectId。
标签: mongodb mongoose mongodb-query geojson mongoose-schema