节点,js – Mongoose – 无法保存地理多边形 – CastError:强制转换为编号失败
我正在尝试将地理点和地理多边形保存到Mongo。 我的testing通过点,但失败的多边形:
CastError:在path“坐标”处投射数值失败,值为“0,0,3,0,3,3,0,3,0,0”
我的模式如下:
var GeoSchema = new Schema({ name: String , coordinates: [Number] }); GeoSchema.index({ coordinates: '2dsphere' });
我成功保存的testing点对象:
geoPoint = new Geo({ coordinates: [2,2], type: 'Point' });
我的testing多边形对象不能保存:
geoPolygon = new Geo({ type: 'Polygon', coordinates: [[ [0,0], [3,0], [3,3], [0,3], [0,0] ]] });
我曾尝试更改为“坐标”的typesdef到一个对象和一个数组,但然后都无法保存。
任何人都可以build议吗?
*更新*
我现在可以使用以下方法传递testing:
模式:
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 }
任何人都可以告诉我为什么我没有看到保存的logging?
编辑:似乎我们可以设置2dsphere仅点,而不是多边形
所以我删除索引,它的工作。
文件: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 }