$ geoNear聚合没有结果

时间:2019-08-02 12:00:29

标签: mongodb aggregation-framework geospatial mongoose-schema mongodb-geospatial

我正在使用Mongoose为某些数据创建基本架构:

const SuppliersSchema = new mongoose.Schema(
  {
    name: { type: String, required: true },
    location: {
      type: {
        type: String,
        enum: ['Point'],
        required: true,
      },
      coordinates: {
        type: [Number],
        index: '2dsphere',
        required: true
      }
    },
  },
);

SuppliersSchema.index({ location: '2dsphere' });

module.exports = mongoose.model('Suppliers', SuppliersSchema, 'suppliers');

一些测试数据如下:

{
    "name": "Bobby",
    "location": {
        "type": "Point",
        "coordinates": [
            -1.588039,
            53.760733
        ]
    }
}

如果我对find$near使用常规的$geometry方法,结果将按预期返回✅

Suppliers.find(
  {
    location: {
      $near: {
        $geometry: { type: 'Point', coordinates: [req.params.lng, req.params.lat] },
        $maxDistance: 5000
      }
    }
  },
  data => {
    return res.status(200).send({ data });
  }
);

我想知道每个supplier的计算距离,因此将$geoNear用作聚合的一部分。这是不返回任何数据的代码段

Suppliers.aggregate(
  [
    {
      $geoNear: {
        near: {
          type: 'Point',
          coordinates: [req.params.lng, req.params.lat]
        },
        spherical: true,
        maxDistance: 5 * 1609.34,
        distanceField: 'distanceFrom'
      }
    }
  ],
  data => {
    return res.status(200).send({ data });
  }
);

有什么主意我可能会错过的吗?使用find方法时,我会明确寻找location,但是寻找$geoNear是从在架构上创建索引得出的吗?

0 个答案:

没有答案