【问题标题】:$geoNear is only valid as the first stage in a pipeline$geoNear 仅作为管道中的第一阶段有效
【发布时间】:2026-02-12 07:40:01
【问题描述】:

我在使用 nodejs 作为服务器端进行聚合时收到以下错误 $geoNear is only valid as the first stage in a pipeline.

聚合对象:

[ { '$geoNear':
     { near: [Object], distanceField: 'distance', spherical: true } },
  { '$lookup':
     { from: 'reviews',
       localField: '_id',
       foreignField: 'restaurant',
       as: 'reviews' } },
  { '$project':
     { logo: '$$ROOT.logo',
       name: '$$ROOT.name',
       cuisine: '$$ROOT.cuisine',
       rate: [Object],
       reservation: '$$ROOT.reservation',
       closeAt: '$$ROOT.closeAt',
       openAt: '$$ROOT.openAt',
       recommendationsLength: [Object],
       isLive: '$$ROOT.isLive',
       avgCost: '$$ROOT.avgCost',
       creationDate: '$$ROOT.creationDate',
       distance: '$$ROOT.distance' } },
  { '$sort': { distance: 1 } } ]

知道为什么会出现上述错误吗?

【问题讨论】:

  • 它在mongo shell 中工作吗?
  • 我没有在 monogo shell 中尝试过我只在 nodejs @Oleg 上工作
  • 那就试试shell吧。
  • 通过聚合管道的代码是什么?它是否在将其发送到 MongoDB 服务器之前添加了另一个阶段?
  • 尝试在您的 mongodb 上启用数据库分析,这样您就可以看到发送的确切查询。

标签: javascript node.js database mongodb geolocation


【解决方案1】:

检查您是否有任何预中间件函数执行聚合。如果是这样,那么这很可能是错误的根源。

【讨论】:

  • 请求前不添加中间件。这是非常直接的
【解决方案2】:

确保您正在查看的字段已在您的 $project 中指明。就像我遇到了这个错误:

[
  {
    $project: {
      title: 1,
      date: 1,
  }
  {
    $match: {
      company, //company is a variable
    },
  },
]

你明白了。

然后我遇到类似问题的另一个原因是 $sort 和 $match 不能出现在 $search 之前,所以请尝试重新排序您的管道。

【讨论】:

    最近更新 更多