首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么mongodb会返回地理索引错误?

为什么mongodb会返回地理索引错误?
EN

Stack Overflow用户
提问于 2019-06-12 14:00:54
回答 1查看 2.4K关注 0票数 1

我正在构建一个应用程序,其中用户可以发布工作,我可以加载的工作,是接近当前用户。在客户端,我发布查询,然后在后端使用这些查询来响应我附近用户的结果。我没有得到结果,而是得到了索引尚未创建的错误。

我使用postpost来测试发送查询,这与从客户端发送没有什么不同。

架构文件

const mongoose = require('mongoose')
const schema = mongoose.Schema;

const userSchema = new schema({
  username: String,
  password: String,
  first_name: String,
  last_name: String,
  email: String,
  phone_number: Number,
  zip_code: Number,
  loc: {
    type: {
      type: String,
      default: "Point"
    },
    coordinates: []
  }
})
userSchema.index({
  'loc': '2dsphere'
});

module.exports = mongoose.model('user', userSchema, 'users')

路由文件

const express = require('express')
const router = express.Router();
const mongoose = require('mongoose')
const jwt = require('jsonwebtoken')
const User = require('../models/user')
const db = 'mongodb+srv://georges:<1997>@cluster0-rm0vl.mongodb.net/users?retryWrites=true&w=majority'

mongoose.connect(db, {
  useNewUrlParser: true
}, (err) => {
  if (err) {
    console.log('The error is' + err)
  } else {
    console.log('the databasee is connected')
  }
})

router.get('/nearme/', (req, res) => {
  let queries = req.query;
  var distance = parseInt(req.query.maxDistance)
  var long = parseInt(req.query.long)
  var lat = parseInt(req.query.lat)
  User.find({
    loc: {
      $near: {
        $geometry: {
          type: "Point",
          coordinates: [long, lat]
        },
        $maxDistance: 10.5
      }
    }
  }, function(error, usernearme) {
    if (error) {
      res.status(401).send(error)
    } else {
      if (usernearme.length === 0) {
        res.status(401).send('no user near me')
      } else {
        res.status(200).send({
          usernearme
        })
      }
    }
  })
})

我的错误是

{
  "operationTime": "6701513149272555521",
  "ok": 0,
  "errmsg": "error processing query: ns=users.usersTree: 
  GEONEAR field = loc maxdist = 10.5 isNearSphere = 0\ nSort: {}\
  nProj: {}\
  n planner returned error: unable to find index
  for $geoNear query ",
  "code": 2,
  "codeName": "BadValue",
  "$clusterTime": {
    "clusterTime": "6701513149272555521",
    "signature": {
      "hash": "tsfDSZp+cZIi6WDoULsy/NH+BQ0=",
      "keyId": "6696267117303431169"
    }
  },
  "name": "MongoError"
}

正如您所看到的,索引已经在模式文件中创建。当我传入经度、纬度和距离的查询值以返回我附近的用户时,我就会得到这个错误。任何帮助都会很好,谢谢。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56555547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档