mongodb - 使用 $geoNear 在使用 maxDistance 时给出“查询 GeoJSON 点时,geo close 仅​​接受一个参数”

Uch*_*ena 4 mongoose mongodb geojson node.js geonear

这似乎是一个常见的错误,但我似乎无法使其与我见过的所有建议一起工作。这是我的设置:

// point.js (based on mongoose recommended subdocument pattern for reusing the GeoJSON definition
// see here https://mongoosejs.com/docs/geojson.html)
const mongoose = require('mongoose');

const pointSchema = new mongoose.Schema({
    type: {
        type: String,
        enum: ['Point'],
        required: true
    },
    coordinates: {
        type: [Number],
        required: true,
    }
});

exports = pointSchema;
Run Code Online (Sandbox Code Playgroud)
// user.js
var schema = new Schema({
  location: {
    type: pointSchema,
  },
  ...
});

schema.index({ location: '2dsphere' });
var User = mongoose.model('User', schema);
Run Code Online (Sandbox Code Playgroud)
// routeHandler.js
          const near = { type: 'Point', coordinates: [lng, lat] };
          User.aggregate([
            { $geoNear: {
              near,
              distanceField: 'dist',
              maxDistance: 100000,
              spherical: true,
            } },
            ...
          ]).exec((err, results) => {
            console.log('error or results:', err, results);
          });
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

MongoError: 无法确定查询系统是否可以提供覆盖投影::,原因是::geo close 在查询 GeoJSON 点时仅接受一个参数。发现额外字段:$maxDistance:100000.0

我见过的大多数线程都表明这是索引问题,但您可以看到user.js我直接调用

schema.index({ location: '2dsphere' });
Run Code Online (Sandbox Code Playgroud)

没有任何运气。

我真的很感激任何建议,谢谢!

小智 7

我遇到了同样的问题,并经历了很多解决方案,但其中任何一个都不起作用,因为 真正的问题在于数据

在我的模型中,2dsphere 索引是正确的,但使用 2dshpere 时,数据库中的位置应采用位置格式:[ lng,lat ],这是主要问题。因为 mongodb 不会验证这种格式的位置数组。

验证数据库中的数据和查询时指定的点都应该是正确的格式。

希望它能帮助别人!

  • 是的,确实如此。就我而言,问题是我以字符串而不是数字的形式提供坐标。 (4认同)

Adh*_*tal 5

我也遇到了同样的错误,经过大量研究后我发现运行聚合查询的错误。我将坐标作为字符串数组传递,它应该是数字数组。

{
        $geoNear: {
          near: {
            type: "Point",
            coordinates: [103.83797, 1.46103],
          },
          distanceField: "dist.calculated",
          maxDistance: distance,
          includeLocs: "dist.location",
          spherical: true,
        },
      },
Run Code Online (Sandbox Code Playgroud)