【问题标题】:How to use aggregate with $near mongoose?如何在 $near mongoose 中使用聚合?
【发布时间】:2020-07-06 13:34:04
【问题描述】:

我试图在特定位置附近随机获取 20 种食物。当我使用 find 它有效但如何使用 $near 的聚合 架构:

const foodSchema = new Schema({
      foodName: {
        type: String,
        required: true
      },
      image: {
        type: String,
        required: true
      },
      price: {
        type: String,
        required: true
      },
      shopName: {
        type: String,
        required: true
      },
      isVerified:{
        type:Boolean,
        default:false,
        required:true
      },
      isEnabled:{
        type:Boolean,
        default:false,
        required:true
      }
      ,
      location: {
        type: { type: String },
        coordinates: [],
        
       },
      shopId:{
        type: Schema.Types.ObjectId,
        ref: 'Shop',
        required: true
      }
      
    });
    
    foodSchema.index({ location: "2dsphere" });

Food.aggregate([{$match:{isEnabled:true,location: {
        $near: {
         $maxDistance: 10000,
         $geometry: {
          type: "Point",
          coordinates: [13.3339, 80.1943]
         }
        }
       }}}])
      .then(data=>{
        console.log(data);
        res.render('user/home',{
          pageTitle:"UiMart",
          foodlist:data
        });
      })
      .catch(err=>{
        console.log(err);
        res.send("err");
      });

MongoError:在此上下文中不允许使用 $geoNear、$near 和 $nearSphere 如何使用 $near mongoose 的聚合函数来获取特定位置附近的随机食物

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    你可以试试这样的:

    Food.aggregate
    ([
       {
         $geoNear: {
            near: { type: "Point", coordinates: [13.3339, 80.1943] },
            distanceField: "dist.calculated",
            maxDistance: 10000,
            query: { "isEnabled": true }
         }
       }
    ])
    

    在聚合框架中,$geoNear 应该是管道中的第一个,您可以使用query 来过滤结果,而不是使用match

    【讨论】:

      猜你喜欢
      • 2020-03-22
      • 2017-10-19
      • 2020-10-29
      • 2018-03-10
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 2020-01-31
      • 2014-08-09
      相关资源
      最近更新 更多