我正在构建一个应用程序,用户可以在其中发布职位,并且可以加载当前用户附近的职位。在客户端,我发布查询,然后在后端使用这些查询以响应我附近的用户的结果。没有得到结果,而是得到一个尚未创建索引的错误。
我正在使用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"
}
,如您所见,索引已在模式文件中创建。传递经度,纬度和距离的查询值以返回附近的用户时,会出现此错误。 任何帮助都将非常感谢。