简体   繁体   中英

Mongoose unable to perform $near query on array of locations

I've tried looking for solutions and I've read parts of the documentation for the $near and $geoNear queries but I have not been successful.

var userSchema = new Schema({
  zipcode : {
    formatted : {type : String, required : false, default : ""},
    geo : { type: [Number], default: [0,0]} // long, lat
  }
});
userSchema.index({"zipcode.geo" : '2d'});

ON A DIFFERENT FILE

var locationSchema = new Schema({
  formatted : {type : String, unique : false, required : true},
  geo : { type: [Number], default: [0,0]}
});

locationSchema.index({geo: '2d'});

var storeSchema = new Schema({
  locations : [locationSchema],
});

On my controller

let nearQuery = {
  $near : [ user.zipcode.geo[0], user.zipcode.geo[1]],
  spherical: true,
  $maxDistance: 7000
}
Stores.find(locations : nearQuery).exec(function(error, doc) {

});

But i end up getting the error - "Error: Can't use spherical with Array."

When I remove

spherical : true

I get the error - " planner returned error: unable to find index for $geoNear query"

I know i am doing something wrong, I just cant figure out how to fix it. How can I fix this? or What is the best way of doing this?

Thank you in advance.

Turns out I was using the wrong syntax for the query and was trying to run the query on the locations field, while I should have done it on the locations.geo field.

https://docs.mongodb.com/manual/tutorial/query-a-2d-index/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM