我有一个小型数据库,其中包含我手动添加的位置,并且我试图通过minDistance和maxDistance对其进行过滤。
这就是猫鼬模式
var schema = new Schema({
name: {
type: String,
unique: false,
required: true
},
location: {
type: [Number], // [<longitude>, <latitude>]
index: '2dsphere', // create the geospatial index
required: false // true senare
}
});
这是用于获取附近地点的方法:
schema.statics.getNearby = function (longitude, latitude, minDistance, maxDistance, callback) {
if ((longitude || latitude) === undefined) return new ModelError("location or radius is missing");
var Places = this;
var point = { type: "Point", coordinates: [ longitude, latitude]};
Places.geoNear(point, { minDistance: minDistance, maxDistance : maxDistance},
function(err, activities, stats) {
if (err) return callback(err);
callback(null, activities);
});
};
这是执行此方法时得到的错误代码:
500 Error
at Error.MongoError (/home/ec2-user/bored_server/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:13:17)
at Function.MongoError.create (/home/ec2-user/bored_server/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:31:11)
at /home/ec2-user/bored_server/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:768:66
at Callbacks.emit (/home/ec2-user/bored_server/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:84:3)
at null.messageHandler (/home/ec2-user/bored_server/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:218:23)
at Socket.<anonymous> (/home/ec2-user/bored_server/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:259:22)
at Socket.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:765:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:427:10)
让我感到困扰的是,使用mongodb可以执行这样的查询,并且效果很好。
db.places.find({
location: {
$nearSphere : {
$geometry: {
type: "Point",
coordinates: [ 18, 58] },
$minDistance: 0,
$maxDistance: 1000000
}
}
}
)
编辑1:
他的解决方案是他应该以米为单位指定maxDistance值,我看不到这对我有什么帮助,因为无论我将哪个值指定为maxdistance,都会出现错误。谢谢
最佳答案
我发现解决方案minDistance和maxDistance是字符串类型,对于maxDistance可以正常工作,但是对于minDistance,我不得不将其转换为float或int。
肮脏的解决方案将是此代码:
schema.statics.getNearby = function (longitude, latitude, minDistance, maxDistance, callback) {
if ((longitude || latitude) === undefined) return new ModelError("location or radius is missing");
var Places = this;
var point = { type: "Point", coordinates: [ longitude, latitude]};
Places.geoNear(point, { minDistance: parseFloat(minDistance), maxDistance : maxDistance},
function(err, activities, stats) {
if (err) return callback(err);
callback(null, activities);
});
};
现在,仅当minDistance为字符串类型时才需要这样做。
谢谢。