我正在尝试查找位于所提供坐标 1 公里半径范围内的所有用户,无论方向如何。但是,我在查询执行时遇到了问题。
我还尝试了index: 2d而不是2dsphere和其他猫鼬属性,例如$near,$nearSphere,但它们都没有提供我正在寻找的结果。
Mongoose Query
User.find({
location: {
$geoWithin: {
$centerSphere: [[longitude, latitude], 1 / 6371],
},
},
})
.then((users) => console.log(users))
.catch((error) => console.log(error));
User Schema
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
index: true,
},
avatar: {
type: String,
},
location: {
type: {
type: String,
enum: ["Point"],
},
coordinates: {
type: [Number],
},
},
},
{
timestamps: true,
}
);
userSchema.index({ location: "2dsphere" });
userSchema.methods.toJSON = function () {
const user = this.toObject();
user.id = user._id.toString();
delete user._id;
delete user.__v;
return user;
};
module.exports = mongoose.model("User", userSchema);
1)坐标顺序:
在
$centerSphere
定义中,确保您按顺序传递 [longitude, latitude]
。第一个值应该是 longitude
,第二个值应该是 latitude
。
2)半径计算:
$centerSphere
的第二个参数是以弧度为单位的半径。您将 1
除以 6371
,即地球的近似半径(以公里为单位)。但是,此计算假设坐标已经以弧度为单位。
如果您的坐标以度为单位(这更常见),您应该将半径转换为弧度。公式为:
radiusInRadians = radiusInKilometers / 6371.0
.
这是您的查询的更正版本:
User.find({
location: {
$geoWithin: {
$centerSphere: [[longitude, latitude], radiusInKilometers / 6371.0],
},
},
})
.then((users) => console.log(users))
.catch((error) => console.log(error));
确保将
radiusInKilometers
替换为要用于查询的实际半径(以公里为单位)。
如果问题仍然存在,您可能需要验证文档的 location
字段是否已正确填充设置为 type
的 Point
以及作为 coordinates
数组的 [longitude, latitude]
。