Reputation: 6086
I am trying to save a Geo Point and a Geo Polygon to Mongo. My tests pass for the Point, but fail for the polygon with:
CastError: Cast to number failed for value "0,0,3,0,3,3,0,3,0,0" at path "coordinates"
My schema is as follows:
var GeoSchema = new Schema({
name: String
, coordinates: [Number]
});
GeoSchema.index({ coordinates: '2dsphere' });
My test point object which successfully saves:
geoPoint = new Geo({
coordinates: [2,2],
type: 'Point'
});
My test polygon object which fails to save:
geoPolygon = new Geo({
type: 'Polygon',
coordinates: [[ [0,0], [3,0], [3,3], [0,3], [0,0] ]]
});
I have tried changing the type def for "coordinates" to an object and an array, but then both fail to save.
Can anyone advise?
* UPDATE *
I can now get the tests passing using:
schema:
var GeoSchema = new Schema({
coordinates : { type: [], index: '2dsphere' },
type: String
});
Point object:
geoPoint = new Geo({
geo: {
type: 'Point',
coordinates: [2,2]
}
});
Polygon:
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] ]
]
}
});
However when I query the db directly I just see:
db.geos.find()
{ "_id" : ObjectId("52b73de00b4dfee427000005"), "__v" : 0 }
{ "_id" : ObjectId("52b73de00b4dfee427000006"), "__v" : 0 }
Can anyone advise why I do not see the saved records?
Upvotes: 2
Views: 1772
Reputation: 18956
Edit: It seem that we can set 2dsphere on Point only, not Polygon
so I remove index and it worked.
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);
})
terminal:
$mongo --version
MongoDB shell version: 2.5.5-pre-
npm install mongoose
node app
output:
{ '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 }
Upvotes: 2