I am frustrated about mongodb geonear aggregate query, for each response i get error like this :
{"name":"MongoError","message":"geoNear command failed: { ok: 0.0, errmsg: \"error processing query: ns=Lab.assoprofiles limit=100Tree: GEONEAR field=loc maxdist=50000 isNearSphere=1\nSort: {}\nProj: { $pt: { $meta: \"geoNearPoin...\", code: 2, codeName: \"BadValue\" }","ok":0,"errmsg":"geoNear command failed: { ok: 0.0, errmsg: \"error processing query: ns=Lab.assoprofiles limit=100Tree: GEONEAR field=loc maxdist=50000 isNearSphere=1\nSort: {}\nProj: { $pt: { $meta: \"geoNearPoin...\", code: 2, codeName: \"BadValue\" }","code":16604,"codeName":"Location16604"}
This how i designed the collection :
const mongoose = require("mongoose");
var Schema = mongoose.Schema;
var AssoSchema = new mongoose.Schema({
userId:{ type: mongoose.Schema.Types.ObjectId, ref: "User"},
picture : String,
telephone: {
type: String,
unique: false
},
loc: {
type: [Number], // [<longitude>, <latitude>]
index: "2d" // create the geospatial index
},
},{timestamps: true})
var Asso = mongoose.model('AssoProfile', AssoSchema);
module.exports = Asso;
And query is like this :
const latitude = parseFloat(req.body.latitude);
const longitude = parseFloat(req.body.longitude);
AssoProfile.aggregate([
{
$geoNear: {
near: { type: 'Point', coordinates: [latitude, longitude] },
spherical: true, distanceField: 'distance', maxDistance:7000,
}
}
], function(err, l ){
console.log(JSON.stringify(err));
console.log(l);
})
I don't understand why such simple query throws this error. Thanks for your helps.
I have run same code you have posted above but It didn't work for me... And I think index: 2d
is not an option in mongoose model. And instead I have created index like this and worked for me.
const mongoose = require("mongoose")
var Schema = mongoose.Schema
var AssoSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
picture : String,
telephone: {
type: String,
unique: false
},
loc: Array,
}, { timestamps: true })
AssoSchema.index({ 'loc': '2dsphere' })
var Asso = mongoose.model('AssoProfile', AssoSchema)
module.exports = Asso;