【发布时间】:2018-06-26 16:13:53
【问题描述】:
我在 mongo / mongoose 文档和堆栈溢出中花了一天时间,似乎无法弄清楚这一点。
这是我的基本架构设置:
const mongoose = require('mongoose');
const config = require('./config/config');
const db = mongoose.createConnection(config.uri, { autoIndex: false });
const storeSchema = mongoose.Schema({
name: String,
location: { type:[Number], index:'2dsphere', required:true },
});
const Store = db.model('Store', storeSchema);
我也试过了:
const storeSchema = mongoose.Schema({
name: String,
location: { type: { type: String }, coordinates: [Number] },
});
storeSchema.index({ location: "2dsphere" });
我在 createConnection 上将 autoIndex 设置为 false,因为在应用程序启动时 Mongoose automatically calls createIndex 并且 $geoNear 查询要求只有一个索引。我想可能是 Mongoose 正在创建重复索引,但这并没有解决问题。
我创建这样的商店记录(简化):
const coordinates = { lng: -122.0266515, lat: 36.9743292 }
Store.create({
name: "My Store",
location: [coordinates.lng, coordinates.lat],
})
这是我返回错误的查询:
const location = { longitude: -122.026423, latitude: 36.974538 }
// above coordinates are near the 'My Store' record's coordinates.
const point = {
type: "Point",
coordinates: [location.longitude, location.latitude]
}
Store.aggregate([{
$geoNear: {
near: point,
distanceField: "dist.calculated",
maxDistance: 100000,
spherical: true
}
}
])
.then((results) => console.log(results))
.catch((error) => console.log(error));
这是我得到的“geoNear 没有地理索引” 错误:
{ MongoError: geoNear command failed: { ok: 0.0, errmsg: "no geo indices
for geoNear", operationTime: Timestamp(1529989103, 8), $clusterTime: {
clusterTime: Timestamp(1529989103, 8), signature: { hash: BinData(0,
0000000000000000000000000000000000000000), keyId: 0 } } }
at queryCallback (/Users/`...`/node_modules/mongodb-
core/lib/cursor.js:244:25)
at /Users/`...`/node_modules/mongodb-
core/lib/connection/pool.js:544:18
at process._tickCallback (internal/process/next_tick.js:150:11)
name: 'MongoError',
message: 'geoNear command failed: { ok: 0.0, errmsg: "no geo indices for
geoNear", operationTime: Timestamp(1529989103, 8), $clusterTime: {
clusterTime: Timestamp(1529989103, 8), signature: { hash: BinData(0,
0000000000000000000000000000000000000000), keyId: 0 } } }',
operationTime: Timestamp { _bsontype: 'Timestamp', low_: 8, high_:
1529989103 },
ok: 0,
errmsg: 'geoNear command failed: { ok: 0.0, errmsg: "no geo indices for
geoNear", operationTime: Timestamp(1529989103, 8), $clusterTime: {
clusterTime: Timestamp(1529989103, 8), signature: { hash: BinData(0,
0000000000000000000000000000000000000000), keyId: 0 } } }',
code: 16604,
codeName: 'Location16604',
'$clusterTime':
{ clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 8, high_:
1529989103 },
`enter code here`signature: { hash: [Binary], keyId: [Long] } } }
当我 console.log storeSchema.index()._indexes 我得到以下信息:
[ [ { location: '2dsphere' }, {} ], [ {}, {} ] ]
...所以索引似乎在那里。
我还尝试在运行查询 after seeing the following stack overflow conversation 之前调用 ensureIndexes。
Store.ensureIndexes({location: '2dsphere'})
【问题讨论】:
标签: node.js mongodb mongoose geospatial geocoding