Skip to content

Instantly share code, notes, and snippets.

@mariohmol
Last active March 24, 2017 03:54
Show Gist options
  • Save mariohmol/0cfebdcbdd885bf71e6f79e629f8eb63 to your computer and use it in GitHub Desktop.
Save mariohmol/0cfebdcbdd885bf71e6f79e629f8eb63 to your computer and use it in GitHub Desktop.
Trying to make geospatial queries in mongoose
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var assert = require('assert')
console.log('\n===========');
console.log(' mongoose version: %s', mongoose.version);
console.log('========\n\n');
var dbname = 'testing_geojsonPoint23';
mongoose.connect('localhost', dbname);
mongoose.connection.on('error', function () {
console.error('connection error', arguments);
});
// schema
var schema = new Schema({
loc: {
type: { type: String },
coordinates: []
},
area: {
type: { type: String, default: 'Polygon' },
coordinates: { type: Array, required: true}
}
});
schema.index({ loc: '2dsphere' });
schema.index({ area: '2dsphere' });
var A = mongoose.model('A', schema);
mongoose.connection.on('open', function () {
//mongoose.connection.db.ensureIndex({ 'schema.area.coordinates': '2dsphere' });
A.on('index', function (err) {
if (err) return done(err);
A.create({loc: { type: 'Point', coordinates: [-179.0, 0.0] },
area: { type: 'Polygon', coordinates: [[
[
-44.12933349609375,
-19.717585810896803622
],
[
-43.792877197265625,
-19.718878576562225646
],
[
-43.8155364990234375,
-20.153296932840667921
],
[
-44.1794586181640625,
-20.109457638447803873
],
[
-44.129333496093757105,
-19.717585810896803622
],
[
-44.12933349609375,
-19.717585810896803622
]
]]
}}, function (err) {
if (err) return done(err);
A.find({ area:{
$near:
{
type: 'Point', coordinates: [-43.941932916641235,-19.931718548878326]
}
}
} , function (err, docs) {
if (err) return done(err);
console.log("FOUND DOCS: ",docs);
done();
});
});
});
});
function done (err) {
if (err) console.error(err.stack);
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close();
});
}
/**
* THIS FAILS
{ area:
{
$geoWithin: {
$geometry:
{
type: 'Point', coordinates: [-43.941932916641235,-19.931718548878326]
}
}
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment