猫鼬找不到$geoNear查询的索引



尝试根据位置查询模型时收到此错误。

在结合一些关于 SO 的答案后,这里是完整的实现。

// model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ModelSchema = new Schema({
  location: {
    type: [Number],
    index: '2dsphere'
  }
});
ModelSchema.index({ location: 1});
module.exports = mongoose.model('model', ModelSchema);

控制器

// controller.js
Model = require('path/to/model')
exports.getByLocation = function(req, res, next) {
  var coords = [+req.query.lon, +req.query.lat];
  Model.where('location').near({
      center: {
          type: 'Point',
          coordinates: coords
      }
    })
    .then(function(docs) {
      res.json(docs);
    })
    .catch(next);
}

希望这对:)有所帮助

最新更新