【问题标题】:Mongoose select function with aggregate or near functions具有聚合或邻近功能的猫鼬选择功能
【发布时间】:2019-06-13 10:41:37
【问题描述】:

我有一个名为 Rest 的模型,它有很多列,我只想在其中获取一些列,同时在该 Rest 模型上应用 near 运算符。这是我的代码

Rest
    .select('rest_status rest_address rest_name rest_contact rest_photo rest_menu rest_avg_rating')
    .aggregate().near({
      near:[parseFloat(req.body.lng),parseFloat(req.body.lat)],
      maxDistance:100000,
      spherical:true,
      distanceField:"dist.calculated"
    })
    .then(rests =>{
      // const response=[];
      //     for(const rest of rests){
      //       console.log(rest);
      //       response.push(rest);
      //     }
      res.send({rests,response_status});
    }).catch(err => res.send(err));

当我这样尝试时。我得到一个错误,选择不是一个函数。我尝试更改选择位置,例如在聚合下方和附近,但它没有用。我是这只猫鼬的新手,请告诉我是否有任何功能或方法可以从我的模型中获取有限的列。 我忘了提到附近和选择,当另一个不使用时工作正常,还请帮助我更改从模型获得的数据

【问题讨论】:

  • 嘿,加了一个答案,看看,我加了一个答案。

标签: node.js mongodb express mongoose mongodb-query


【解决方案1】:

你可以在下面做这样的事情:

Rest.aggregate([
  {
    $geoNear: {
      near: {
        type: "Point",
        coordinates: [parseFloat(req.body.lng), parseFloat(req.body.lat)]
      },
      maxDistance: 100000,
      spherical: true,

      distanceField: "dist.calculated"
    }
  },
  {
    $project: {
      rest_status: 1,
      rest_address: 1,
      rest_name: 1,
      rest_contact: 1,
      rest_photo: 1,
      rest_menu: 1,
      rest_avg_rating: 1
    }
  }
  //even you can add limit skip below , if u need
  ,{$limit:<Number>},
  { $skip: <Number>}
]
//depends on your mongo version you may need to set cursor as well.
,
{ cursor: { batchSize: <Number or keep 0> } }
)
  .then()
  .catch();

注意:在执行查询之前,请确保您已将 2dsphere 索引添加到您的 dist.calculated 字段

如果聚合 $project 用于您想要对 .select 执行的操作

我没有使用.near(),而是使用了$geoNear

如果您想使用限制跳过,您可以按照示例进行操作,否则可以将其删除。

您也可以根据您的要求添加distanceMultiplierincludeLocs 字段。

在上面,取决于您可能需要使用cursor 聚合的mongoDB 版本。
如果没有,您可以不使用cursor 继续。

希望这会有所帮助。

如果仍有错误,请发表评论。

【讨论】:

  • 很抱歉这么晚的回复,感谢您的回答。如何根据字段 [ex: rest_status : "available"] 以及当前配置过滤结果。我尝试使用 find 但聚合和查找相互冲突,最后一个请求你能建议我一个文档或一些网站来理解这个功能,我目前只使用功能有限的猫鼬函数 [find,near 等]
  • 好吧,那你也可以加$match,其中yu可以通过条件。看看这里:docs.mongodb.com/manual/reference/operator/aggregation/match
  • 太棒了,@gouthamreddy 如果它帮助了你,并且认为它可能是正确的答案,你也可以给个赞。 :)
  • 我做了,但 StackOverflow 说我的声誉不足以显示我给予的支持
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 2013-05-09
  • 2019-02-18
  • 2015-09-30
相关资源
最近更新 更多