【问题标题】:mongoose $geoNear, $near, and $nearSphere are not allowed in this context在此上下文中不允许使用 mongoose $geoNear、$near 和 $nearSphere
【发布时间】:2020-03-29 20:57:10
【问题描述】:

这是我的架构:

const userSchema = mongoose.Schema({
    coordinates: {
        type: { type: String },
        coordinates: [],
       },
})

然后我添加这个:

userSchema.index({ coordinates: "2dsphere" });

我想找到一个半径内的所有坐标。这是我正在调用的方法:

router.post('/users/query', async(req,res)=>{
    var pageOptions = {
        page: req.body.page || 0,
        limit:  10
    }
    const query ={     location: {
        $near: {
         $maxDistance: req.body.searchQuery.maxDistance,
         $geometry: {
          type: "Point",
          coordinates: req.body.searchQuery.coordinates
         }
        }
       }} 
       console.log(query)
    User.find(query)
    .skip(pageOptions.page*pageOptions.limit)
    .limit(pageOptions.limit)
    .exec(function (error, users) {
        if(error) { res.status(500).json({error}); return; };
        User.countDocuments(query).exec((error,total)=>{
            if(error) { 
                res.status(500).json({error})
            }else{
                res.status(200).json({users,total});

             };
        })
    })
})

我在这篇文章中这样做了:https://medium.com/@galford151/mongoose-geospatial-queries-with-near-59800b79c0f6

但我得到错误 $geoNear, $near, and $nearSphere are not allowed in this context。有人知道为什么吗?

这是我的搜索查询:

{ searchQuery: 
{ coordinates: [ 9.993681899999956, 53.5510846 ],
maxDistance: 1000 } }

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    使用 count 方法代替 countDocuments 方法

    【讨论】:

    • 这不是一个很好的答案。 .count() 已弃用,应使用 .countDocuments()。要获得正确的解决方案,请查看 MongoDB 论坛上的错误报告以了解此问题 --> jira.mongodb.org/browse/NODE-1834
    猜你喜欢
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 2023-04-02
    相关资源
    最近更新 更多