调用getdata()api时,显示错误: "$geoNear requires a 2d or 2dsphere index, but none were found"
有人这样说: db.collection.createIndex( { <location field> : "2dsphere" } )
但我不知道我想把这一行,所以请帮助我在节点新
下面是我的模式和getdataapi
postschema.js
var schema = new Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
},
price: {
type: Number
},
details: {
type: String
},
location: {
type: {
type: String,
default: "Point"
},
coordinates: [Number]
}
}, {
collection: 'posts',
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
},
versionKey: false
})
schema.indexes({ location: '2dsphere' })
getdataapi
getAllPosts: async (req, res) => {
try {
let filterQuery = {
userId: { $ne: req.user._id },
}
let aggregateQuery = [];
aggregateQuery.push({
$geoNear: {
near: { type: "Point", coordinates: req.user.location.coordinates },
distanceField: "distanceFrom",
spherical: true,
query: filterQuery,
distanceMultiplier: 0.001
}
})
let posts = await Post.aggregate(aggregateQuery);
return res.status(200).json({
success: true,
message: 'Posts get successfully',
data: posts
})
} catch (err) {
return res.status(400).json({
success: false,
message: err && err.message ? err.message : 'Something went wrong',
data: {}
})
}
}
1条答案
按热度按时间wsewodh21#
你能试着换一个新的吗
indexes
具有index
在模式定义中查看有关创建索引的详细信息