Node.js 如何与$near mongoose一起使用聚合?

Node.js 如何与$near mongoose一起使用聚合?,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我试图在特定地点附近随机获得20种食物。当我使用find时,它可以工作,但是如何使用$near的聚合 模式: const foodSchema = new Schema({ foodName: { type: String, required: true }, image: { type: String, required: true }, price: {

我试图在特定地点附近随机获得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" });

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

您可以尝试以下方法:

Food.aggregate
([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [13.3339, 80.1943] },
        distanceField: "dist.calculated",
        maxDistance: 10000,
        query: { "isEnabled": true }
     }
   }
])
在聚合框架中,
$geoNear
应该是管道中的第一个,您可以使用
查询
来过滤结果,而不是使用
匹配

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