Chens
Chens

Reputation: 1

Node - using MongoDB for aggregate and geoNear

I'm trying to write a simple node app for finding nearby users. I'm using Mongo 5.9.11 for the aggregate function and the $geoNear, but unfortunately when I try to run the app and find users, I get back an empty array - not even an error message. Can anyone see the problem here? Should I use differently the aggregation or maybe to define the schema in a different way? Please help Here's the code:

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);
});

Also, the code for the schema:

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;

Upvotes: 0

Views: 188

Answers (0)

Related Questions