我正在使用Mongoose为某些数据创建基本架构:
const SuppliersSchema = new mongoose.Schema(
{
name: { type: String, required: true },
location: {
type: {
type: String,
enum: ['Point'],
required: true,
},
coordinates: {
type: [Number],
index: '2dsphere',
required: true
}
},
},
);
SuppliersSchema.index({ location: '2dsphere' });
module.exports = mongoose.model('Suppliers', SuppliersSchema, 'suppliers');
一些测试数据如下:
{
"name": "Bobby",
"location": {
"type": "Point",
"coordinates": [
-1.588039,
53.760733
]
}
}
如果我对find
和$near
使用常规的$geometry
方法,结果将按预期返回✅
Suppliers.find(
{
location: {
$near: {
$geometry: { type: 'Point', coordinates: [req.params.lng, req.params.lat] },
$maxDistance: 5000
}
}
},
data => {
return res.status(200).send({ data });
}
);
我想知道每个supplier
的计算距离,因此将$geoNear
用作聚合的一部分。这是不返回任何数据的代码段
Suppliers.aggregate(
[
{
$geoNear: {
near: {
type: 'Point',
coordinates: [req.params.lng, req.params.lat]
},
spherical: true,
maxDistance: 5 * 1609.34,
distanceField: 'distanceFrom'
}
}
],
data => {
return res.status(200).send({ data });
}
);
有什么主意我可能会错过的吗?使用find
方法时,我会明确寻找location
,但是寻找$geoNear
是从在架构上创建索引得出的吗?