尝试对monggodb进行查询时出现此错误:
error processing query: ns=makenoisetogether.users limit=10Tree: GEONEAR field=location maxdist=10000 isNearSphere=0 Sort: {} Proj: { name: 1, location: 1, musicLinks: 1, genres: 1, photo: 1, slug: 1 } planner returned error: unable to find index for $geoNear query
我有一个控制器试图根据纬度和纬度上的参数获取用户:
const coordinates = [req.query.lng, req.query.lat].map(parseFloat);
const q = {
location: {
$near: {
$geometry: {
type: 'Point',
coordinates
},
$maxDistance: 10000 // 10km
}
}
};
const users = await User.find(q).select('name location musicLinks genres photo slug').limit(10);
res.json(users);
};
此行发生错误:
const users = await User.find(q).select('name location musicLinks genres photo slug').limit(10);
任何想法可能是什么问题?
这是我的用户模式,在这里我已经为2dsphere添加了位置索引:
const userSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true,
trim: true,
validate: [validator.isEmail, 'Invalid Email Address'],
required: 'Please Supply an email address'
},
created: {
type: Date,
default: Date.now
},
location: {
type: {
type: String,
default: 'Point'
},
coordinates: [{
type: Number,
required: 'You must supply coordinates!'
}],
address: {
type: String,
required: 'You must supply an address!'
},
vicinity: {
type: String,
},
},
});
userSchema.index({ location: '2dsphere' })