After reading many questions that are SO close to mine, and reading the MongoDB docs and Mongoose docs, I still cannot answer my question.
Using express 4.13.4, mongoose 4.4.10, mongodb 2.1.14 on Node 4.4.0
My Mongoose Location schema:
var schema = new Schema({
type: {type: String},
coordinates: []
},{_id:false});
var model = mongoose.model('LocationModel',schema);
module.exports = {
model : model,
schema : schema
};
My CatalogModel
schema (what I write to Mongo):
var locationSchema = require('./locationModel').schema;
var schema = new Schema({
title : String,
format: {type: String, maxlength: 4},
location: {type: locationSchema, required:true},
otherStuff: String
});
schema.index({location: '2dsphere'}); // Ensures 2dsphere index for location
model = mongoose.model('CatalogModel',schema);
I create a concrete example and write to MongoDB (this works fine... in that I can query it in Mongo)
var polyEntry = new CatalogModel({
title:"I am just a Polygon",
otherStuff: "More stuff here",
location:{
type:'Polygon',
coordinates:[[[0,1],[0,2],[1,2],[0,1]]]
}
});
In Mongo, I asked the collection for the indexes:
db.catalogmodels.getIndexes()
And this is what it says (not entirely sure what this means)
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.catalogmodels"
},
{
"v" : 1,
"key" : {
"location" : "2dsphere"
},
"name" : "location_2dsphere",
"ns" : "test.catalogmodels",
"background" : true,
"2dsphereIndexVersion" : 3
}
]
I can do a db.catalogmodels.find()
and get my document back.
{
"_id" : ObjectId("12345678901234566778"),
"title" : "I am just a Polygon",
"location" : {
"type" : "Polygon",
"coordinates" : [ [ [ 0, 1 ], [ 0, 2 ], [ 1, 2 ], [ 0, 1 ] ] ]
},
"__v" : 0
}
I can even do a $geoWithin call in Mongo:
db.catalogmodels.find(
{
location:{
$geoWithin:{
$geometry:{
type:"Polygon",
"coordinates":[[[-1,0],[-1,3],[4,3],[4,0],[-1,0]]]
}
}
}
})
But here's the actual question:
Mongoose keeps telling me [Error: Can't use $geoWithin]
var geoJson = {
"type" : "Polygon",
"coordinates" : [[[-1,0],[-1,3],[4,3],[4,0],[-1,0]]]
};
CatalogModel
.find()
.where('location').within(geoJson)
.exec(function(err,data){
if ( err ) { console.log(err); }
else {console.log("Data: " + data);}
db.close()
});
I also replaced the .find().where().within() call to:
CatalogEntryModel.find({
location:{
$geoWithin:{
$geometry:{
type:"Polygon",
"coordinates":[[[-1,0],[-1,3],[4,3],[4,0],[-1,0]]]
}
}
}
})
.exec(function(err,data){
if ( err ) { console.log(err); }
else {console.log("Data: " + data);}
db.close();
});
Is there a reason Mongoose does not like the $geoWithin call? The latest API says this should work.