简体   繁体   中英

Mongoose, geospatial query for users

I'm currently working with nodeJS, using express and mongoDB and mongoose for an ORM. When I create a User and save them to the database I would like to query their location and save it. This is what I am currently doing, I have a UserSchema and a location Schema.

My userSchema just has the location stored as a string and in the location Schema itself I have

var locationSchema = new mongoose.Schema({
   name: String,
   loc: {
       type: [Number],
       index: '2d'
   }
});

mongoose.model('Location', LocationSchema);

And then in my controller, I have the following

import json from '../helpers/json;
import mongoose from 'mongoose';
var User = mongoose.model('User);
module.exports = function() {
   var obj = {};

   obj.create = function (req, res) {
       var user = new User(req.body);
       user.roles = ['authenticated']
       user.location = getLocation(req);
       user.save(function (err) {
           if (err) {
              return json.bad(err, res);
           }

           json.good({
                 record: user,
           });
      });
    };

   return obj;

   function getLocation (req) {
       var limit = req.query.limit || 10;
       var maxDistance = req.query.distance || 1;
       maxDistance /= 6371;

       var coords = [];
       coords[0] = req.query.longitude;
       coords[1] = req.query.lattitude;

       Location.findOne({
           loc: {
               $near: coords,
               $maxDistance: maxDistance
           }
      }).limit(limit).exec(function (err, location) {
           if (err) {
              console.log(err);
           }

          return location.name;
     });
   }
};

I have also tried using location.find instead of findOne and returning locations[0].name.

The error is thrown says cast to the number failed for value undefined at loc.

Do I need to send the location data to the server from the client side? If so, is there a best method to implement this? I have heard of the HTML5 Geolocation API, but I have never utilized it.

Thank you!

!!! -- UPDATE --- !!

I have started using the Geolocation API on the client side to send this data to the server in the request. I am using angular on the client side like so

(function() {
  'use strict';

  angular.module('opinionated.authentication')
  .controller('SignupController', SignupController);

  /* @ngInject */
  function SignupController ($state, appUsers, appToast) {
    var vm = this;
    vm.reset = reset;
    vm.create = create;
    vm.user = {
        name: '',
        username: '',
        email: '',
        password: ''
   };
   vm.location = {
      lattitude: '',
      longitude: ''
   };

   function create = (isValid) {
      if (isValid) {
        var user = new appUsers.single({
             name: vm.user.name,
             username: vm.user.username,
             email: vm.user.email,
             password: vm.user.password,
             lattitude: vm.location.lattitude,
             longitutde: vm.location.longitude
        });

        user.$save(function (response) {
           if (response.success) {
              appToast('Welcome to Opinionated, ' +     response.res.record.name);
              $state.go('authentication.wizard')
            } else {
              appToast(response.res.messsage);
            }
        });
      } else {
         appToast('Hmm... Something seems to be missing');
      }
    }
      function getPosition() {
          navigator.geolocation.getPosition(updatePosition);
      }

      function updatePosition (position) {
          vm.location.lattitude = position.coords.lattitude;
          vm.location.longitutde = position.coords.longitude;
      }

      getPosition();

     ....

I think it has something to do with how I am getting the coordinates now. My browser prompts me for permission to use my location, so I am at least requesting the data. However, I changed my User Schema to save the lat and long and neither of these values are being saved upon success.

I found my error. I did need to include the Geolocation API to get the users coordinates. I then just saved the coordinates to the database and am using mongo's geo service from there! Everything works fine now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM