我正在尝试编写一个简单的节点应用程序来查找附近的用户。我将 Mongo 5.9.11 用于聚合函数和 $geoNear,但不幸的是,当我尝试运行应用程序并查找用户时,我得到一个空数组 - 甚至没有错误消息。任何人都可以在这里看到问题吗?我应该以不同的方式使用聚合还是以不同的方式定义架构?请帮助这是代码:
router.get('/nearbyUsers', (req, res) => {
User.aggregate([{
$geoNear: {
near: {type: 'point', coordinates: [parseFloat(req.query.lng), parseFloat(req.query.lat)]},
distanceField: "dist.calculated",
maxDistance: 100000,
query: { type: 'public' },
includeLocs: "dist.location",
spherical: true
}
}
])
.then(users=> res.send(users))
.catch(err => res.send(err));
console.log(req.query.lng, req.query.lat);
});
此外,架构的代码:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const GeoSchema = new Schema({
type: {
type: String,
default: "Point"
},
coordinates: {
type: [Number],
index: "2dsphere"
}
});
const UserSchema = new Schema({
name: {
type: String,
required: [true, 'Name field must be filled']
},
rank: {
type: String
},
available: {
type: Boolean,
default: false
},
geometry: GeoSchema
});
const User= mongoose.model('user', UserSchema);
module.exports = User;