MongoDB/Mongoose - Aggregation with geoNear & subdocuments
First a disclaimer: I am not a Node/Mongoose expert so I am hoping you can translate the general formats to Node/Mongoose.
For the error:
errmsg: "exception: 'near' field must be point"
For a '2d' index this cannot be a GeoJson point and instead needs to be a "legacy coordinate pair". e.g.,
{ "$geoNear": { "near": geo.ll, "maxDistance": 40000, "distanceField": "dist.calculated" }}
If you want to use GeoJSON you will need to use a '2dsphere' index.
With that change the $geoNear query will work with the array of points in the query. An example in the shell:
> db.test.createIndex({ "locations": "2d" })> db.test.insert({ "locations": [ [1, 2], [10, 20] ] });> db.test.insert({ "locations": [ [100, 100], [180, 180] ] });> db.test.aggregate([{ "$geoNear": { "near": [10, 10], "maxDistance": 40000, "distanceField": "dist.calculated", num: 1 }}]);{ "result": [{ "_id": ObjectId("552aaf7478dd9c25a3472a2a"), "locations": [ [ 1, 2 ], [ 10, 20 ] ], "dist": { "calculated": 10 } }], "ok": 1}
Note that you only get a single distance per document (the closest point) which is semantically not the same as doing the unwind and then determining the distance to every point. I cannot be sure if that is important for your use case.