我正在尝试将Geo Point和Geo Polygon保存到Mongo。我的测试通过了Point,但是多边形失败了:
CastError:对于路径“coordinates”处的值“0,0,3,0,3,3,0,3,0,0”,转换为数字失败
我的架构如下:
var GeoSchema = new Schema({
name: String
, coordinates: [Number]
});
GeoSchema.index({ coordinates: '2dsphere' });
我的测试点对象成功保存:
geoPoint = new Geo({
coordinates: [2,2],
type: 'Point'
});
我的测试多边形对象无法保存:
geoPolygon = new Geo({
type: 'Polygon',
coordinates: [[ [0,0], [3,0], [3,3], [0,3], [0,0] ]]
});
我尝试将“坐标”的类型def更改为对象和数组,但两者都无法保存。
有人可以提供建议吗?
*更新*
我现在可以使用以下方式进行测试:
模式:
var GeoSchema = new Schema({
coordinates : { type: [], index: '2dsphere' },
type: String
});
点对象:
geoPoint = new Geo({
geo: {
type: 'Point',
coordinates: [2,2]
}
});
多边形:
geoPolygon = new Geo({
geo: {
type: 'Polygon',
coordinates: [
[ [100.0, 0.0], [101.0, 0.0],
[101.0, 1.0], [100.0, 1.0],
[100.0, 0.0] ]
]
}
});
然而,当我直接查询数据库时,我只看到:
db.geos.find()
{ "_id" : ObjectId("52b73de00b4dfee427000005"), "__v" : 0 }
{ "_id" : ObjectId("52b73de00b4dfee427000006"), "__v" : 0 }
有人可以告诉我为什么看不到保存的记录吗?
答案 0 :(得分:2)
编辑: 似乎我们只能在Point上设置2dsphere,而不是Polygon
所以我删除索引并且它有效。
file:app.js
var mongoose = require('mongoose');
mongoose.connect('localhost', 'geo-database');
var GeoSchema = mongoose.Schema({
name: String
, coordinates: []
});
//GeoSchema.index({ coordinates: '2dsphere' });
var Geo = mongoose.model('geos', GeoSchema);
Geo.on('index', function () {
function cb() {
console.log(arguments);
}
geoPoint = new Geo({
coordinates: [2,2],
type: 'Point'
}).save(cb);
geoPolygon = new Geo({
type: 'Polygon',
coordinates: [[ [0,0], [3,0], [3,3], [0,3], [0,0] ]]
}).save(cb);
})
终端:
$mongo --version
MongoDB shell version: 2.5.5-pre-
npm install mongoose
node app
输出:
{ '0': null,
'1': { __v: 0, _id: 52b6e82493d21060b3000001, coordinates: [ 2, 2 ] },
'2': 1 }
{ '0': null,
'1':
{ __v: 0,
_id: 52b6e82493d21060b3000002,
coordinates: [ [ [Object], [Object], [Object], [Object], [Object] ] ] },
'2': 1 }