node.js - 找不到 $geoNear 查询的索引,代码:2,代号:'badValue'
问题描述
这是我的架构
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
skills: [{
type: String
}],
location: {
type: {
type: String,
index: '2dsphere'
},
coordinates: []
}
});
我的查询看起来像这样
User.find({
location: {
$nearSphere: {
$geometry: {
type: "Point",
coordinates: [77.032448, 28.590654]
},
$maxDistance: 2000
}
}
}).find((error, results) => {
if (error) console.log(error);
console.log(results);
});
每当我运行代码时,我都会收到此错误
ok: 0,
errmsg:
'error processing query: ns=StudyJamm.usersTree: GEONEAR field=location maxdist=2000 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
code: 2,
codeName: 'BadValue',
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {}
PS:-我已经试过了User.index({location: "2dsphere"});
我在这里做错了什么?我已经解决了关于 Stack Overflow 的所有类似问题,但没有任何解决方案适合我。
解决方案
该位置将像下面一样存储在 mongoDB 中。
location: {
type: "Point",
coordinates: [-73.856077, 40.848447]
}
因此,只需再次检查您对位置的定义。type
值在这里始终固定为“点”,尝试将其建模为静态值。并且您指定的索引应该在location
not inside type
。
您可以从数据库中检查此查询是否创建了索引
db.getCollection('data').getIndexes()
如果不是,则索引创建存在问题。我从https://mongoosejs.com/docs/api.html#schematype_SchemaType-index得到以下代码
var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
推荐阅读
- php - 使用 array_unshift() 方法从数组中插入多个值
- android - 如果没有互联网并且无法从数据库中检索值,则使用默认值填充 android 中的微调器
- asp.net-mvc - 预编译的 ASP.NET MVC 视图在 Azure 中一段时间后变慢
- video - VirtualDub 安装视频编解码器
- datatable - 如何从 output_value 中找到部分匹配并将其与 dt_datatable 中的值匹配,然后使用找到的部分匹配来添加行
- r - 围绕点坐标创建不重叠的六边形
- batch-file - 如何从批处理文件创建文本文件?
- mysql - MySQL查询以查找所有子元素
- c++ - 运行由 protoc 生成的文件时出现分段错误
- plugins - 在 Dynamics CRM 中的自定义按钮后面创建插件