You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose文本检索查询返回结果缺失location字段的原因是什么

问题原因及修复方案

导致location字段没有返回的核心原因有两个:

  • Schema定义不符合GeoJSON规范
    你当前的location字段配置存在语法错误:将location顶层的type属性设置为了String,导致Mongoose将location识别为字符串类型,而非存储经纬度的GeoJSON对象。Mongoose默认会自动过滤和Schema定义不匹配的字段,因此返回结果中没有location字段。
    正确的GeoJSON 2dsphere点类型的Schema定义如下:
const citySchema = new mongoose.Schema({
  country: {
    type: String,
  },
  name: {
    type: String,
    index: 'text',
  },
  location: {
    type: {
      type: String,
      enum: ['Point'],
      required: true
    },
    coordinates: {
      type: [Number],
      required: true
    }
  }
})
// 设置2dsphere索引
citySchema.index({ location: '2dsphere' })
  • 投影配置未显式指定返回字段
    你在find方法的第二个投影参数中,仅指定了返回textScore元数据。部分场景下如果开启了Mongoose的严格查询配置,未显式指定的非默认字段可能被过滤。可以在投影中手动指定需要返回的字段,修改后的查询代码如下:
public findCitys(city: string) {
  return City.find(
    {
      country: 'AT',
      $text: {
        $search: city,
      },
    },
    {
      score: { $meta: 'textScore' },
      location: 1,
      name: 1,
      country: 1
    }
  )
  .sort({ score: { $meta: 'textScore' } })
  .limit(5)
}

修改Schema后注意校验存量数据的location结构是否符合规范,避免依旧无法正常返回的问题。

内容的提问来源于stack exchange,提问作者Ilijanovic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:24:03