我对 mongodb geonear 聚合查询感到沮丧,对于每个响应,我都会收到如下错误:
{"name":"MongoError","message":"geoNear command failed: { ok: 0.0, errmsg: \"error processing query: ns=Lab.assoprofiles limit=100Tree: GEONEAR field=loc maxdist=50000 isNearSphere=1\nSort: {}\nProj: { $pt: { $meta: \"geoNearPoin...\", code: 2, codeName: \"BadValue\" }","ok":0,"errmsg":"geoNear command failed: { ok: 0.0, errmsg: \"error processing query: ns=Lab.assoprofiles limit=100Tree: GEONEAR field=loc maxdist=50000 isNearSphere=1\nSort: {}\nProj: { $pt: { $meta: \"geoNearPoin...\", code: 2, codeName: \"BadValue\" }","code":16604,"codeName":"Location16604"}
这就是我设计这个系列的方式:
const mongoose = require("mongoose");
var Schema = mongoose.Schema;
var AssoSchema = new mongoose.Schema({
userId:{ type: mongoose.Schema.Types.ObjectId, ref: "User"},
picture : String,
telephone: {
type: String,
unique: false
},
loc: {
type: [Number], // [<longitude>, <latitude>]
index: "2d" // create the geospatial index
},
},{timestamps: true})
var Asso = mongoose.model('AssoProfile', AssoSchema);
module.exports = Asso;
查询是这样的:
const latitude = parseFloat(req.body.latitude);
const longitude = parseFloat(req.body.longitude);
AssoProfile.aggregate([
{
$geoNear: {
near: { type: 'Point', coordinates: [latitude, longitude] },
spherical: true, distanceField: 'distance', maxDistance:7000,
}
}
], function(err, l ){
console.log(JSON.stringify(err));
console.log(l);
})
我不明白为什么这么简单的查询会抛出这个错误。 感谢您的帮助。
我运行了与上面发布的相同的代码,但它对我不起作用......而且我认为
index: 2d
不是猫鼬模型中的选项。相反,我创建了这样的索引并为我工作。
const mongoose = require("mongoose")
var Schema = mongoose.Schema
var AssoSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
picture : String,
telephone: {
type: String,
unique: false
},
loc: Array,
}, { timestamps: true })
AssoSchema.index({ 'loc': '2dsphere' })
var Asso = mongoose.model('AssoProfile', AssoSchema)
module.exports = Asso;
就我而言,我的索引很好,但我用来引用它的
'key'
是错误的。删除该要求,让 Mongo 自动使用所需的索引,并添加所需的 query
对我有用。
$geoNear: {
near: { type: 'Point', coordinates: [latitude, longitude] },
spherical: true,
distanceField: 'distance',
maxDistance: 7000,
// key: 'geometry', // removing this
query: { // adding this
required_index_field: '17',
},
}
query
对我来说是必要的,因为我的索引是复合索引(例如 required_index_field_geometry_2dsphere
),因此需要另一个可访问的字段。