【发布时间】:2019-10-18 05:12:02
【问题描述】:
我正在使用 nodejs、mongoose 和 graphql,我的数据库中有 geojson 2D 坐标,但我无法通过 graphql 查询它们,它总是返回 null
我已尝试使用 https://github.com/ghengeveld/graphql-geojson 中的 PointObject 架构来替换我的 Geometry 架构,但同样的问题
我的代码:
const Geometry = new GraphQLObjectType({
name: 'Geometry',
fields: () => ({
type: {
type: GraphQLString
},
coordinates: {
type: new GraphQLList(GraphQLFloat)
},
}),
})
const AntenneType = new GraphQLObjectType({
name: 'AntenneType',
fields: () => ({
_id: {
type: GraphQLID
},
type: {
type: GraphQLString
},
geometry: {
type: Geometry
},
properties: {
type: Properties
}
}),
});
const query = new GraphQLObjectType({
name: 'Query',
fields: {
antennes: {
type: new GraphQLList(AntenneType),
resolve: (obj, args, context, info) => {
return Antenne.find().limit(2) //Antenne is my mongoose model that return same data as in the data.json file
.then(antennes => {
console.log(antennes)
return antennes
})
}
}
},
});
一组数据:
{
"properties": {
...
},
"geometry": {
"type": "Point",
"coordinates": [
2.231666666667,
49.223611111111
]
},
"_id": "5cf1901b228293201fe248dc",
"type": "Feature"
}
我的 GraphQl 查询:
query{
antennes{
_id
properties{
generation
adm_lb_nom
}
geometry{
coordinates
}
}
}
结果:
{
"data": {
"antennes": [
{
"_id": "5cf1901b228293201fe248dc",
"properties": {
"generation": "2G",
"adm_lb_nom": "SFR"
},
"geometry": {
"coordinates": null
}
}
]
}
}
我还用我的完整架构和数据做了一个要点:https://gist.github.com/yadPe/cb397175a8c39021d0dab2208fe22a4d
我的猫鼬模式(根据@DanielRearden 回答编辑):
const geoSchema = new Schema({
type: {
type: String,
enum: ['Point'],
required: true
},
coordinates: {
type: [Number],
required: true
}
});
const antenneSchema = new Schema({
type: String,
properties: {
sup_id: Number,
tpo_id: Number,
sta_nm_dpt: String,
adr_nm_cp: Number,
generation: String,
coordonnees: String,
sup_nm_haut: Number,
adm_lb_nom: String,
emr_lb_systeme: String,
coord: String,
emr_dt_service: String,
date_maj: String,
code_insee: String,
nat_id: Number,
_id: Number,
com_cd_insee: String,
id: Number,
total_de_adm_lb_nom: String,
sta_nm_anfr: String
},
geometry: {
geoSchema
}
}, { collection: '2G_France' });
module.exports = mongoose.model('Antenne', antenneSchema);
我对猫鼬返回的数据进行了一些控制台日志记录:
Antenne.find().limit(1)
.then(antennes => {
//return antennes
return antennes.map(antenne => {
console.log(antenne.geometry)
console.log(typeof antenne.geometry)
console.log(antenne.geometry.type)
console.log(antenne.geometry.coordinates)
const test = JSON.parse(JSON.stringify(antenne.geometry)) // idk why I need to do that here
console.log(test.type)
console.log(test.coordinates)
return antenne
})
});
得到以下结果:
{ type: 'Point',
coordinates: [ 2.323333333333, 48.346666666667 ] }
object
undefined
undefined
Point
[ 2.323333333333, 48.346666666667 ]
【问题讨论】:
-
嗯。问题不在于您的架构。仅返回您提供的示例数据时,您的代码 works as expected。我怀疑猫鼬没有以我们期望的形状返回数据,即使它正确打印到控制台。您可以更新问题以包含您的猫鼬模式吗?
-
感谢@DanielRearden 帮助我。我已将我的猫鼬模式添加到问题中
标签: javascript node.js mongoose graphql geojson