You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.3 KiB

  1. // import async to make control flow simplier
  2. var async = require('async');
  3. // import the rest of the normal stuff
  4. var mongoose = require('../../lib');
  5. require('./person.js')();
  6. var Person = mongoose.model('Person');
  7. // define some dummy data
  8. var data = [
  9. {
  10. name: 'bill',
  11. age: 25,
  12. birthday: new Date().setFullYear((new Date().getFullYear() - 25)),
  13. gender: 'Male',
  14. likes: ['movies', 'games', 'dogs'],
  15. loc: [0, 0]
  16. },
  17. {
  18. name: 'mary',
  19. age: 30,
  20. birthday: new Date().setFullYear((new Date().getFullYear() - 30)),
  21. gender: 'Female',
  22. likes: ['movies', 'birds', 'cats'],
  23. loc: [1, 1]
  24. },
  25. {
  26. name: 'bob',
  27. age: 21,
  28. birthday: new Date().setFullYear((new Date().getFullYear() - 21)),
  29. gender: 'Male',
  30. likes: ['tv', 'games', 'rabbits'],
  31. loc: [3, 3]
  32. },
  33. {
  34. name: 'lilly',
  35. age: 26,
  36. birthday: new Date().setFullYear((new Date().getFullYear() - 26)),
  37. gender: 'Female',
  38. likes: ['books', 'cats', 'dogs'],
  39. loc: [6, 6]
  40. },
  41. {
  42. name: 'alucard',
  43. age: 1000,
  44. birthday: new Date().setFullYear((new Date().getFullYear() - 1000)),
  45. gender: 'Male',
  46. likes: ['glasses', 'wine', 'the night'],
  47. loc: [10, 10]
  48. }
  49. ];
  50. mongoose.connect('mongodb://localhost/persons', function(err) {
  51. if (err) {
  52. throw err;
  53. }
  54. // create all of the dummy people
  55. async.each(data, function(item, cb) {
  56. Person.create(item, cb);
  57. }, function(err) {
  58. if (err) {
  59. // handler error
  60. }
  61. // let's find the closest person to bob
  62. Person.find({name: 'bob'}, function(err, res) {
  63. if (err) {
  64. throw err;
  65. }
  66. res[0].findClosest(function(err, closest) {
  67. if (err) {
  68. throw err;
  69. }
  70. console.log('%s is closest to %s', res[0].name, closest);
  71. // we can also just query straight off of the model. For more
  72. // information about geospatial queries and indexes, see
  73. // http://docs.mongodb.org/manual/applications/geospatial-indexes/
  74. var coords = [7, 7];
  75. Person.find({loc: {$nearSphere: coords}}).limit(1).exec(function(err, res) {
  76. console.log('Closest to %s is %s', coords, res);
  77. cleanup();
  78. });
  79. });
  80. });
  81. });
  82. });
  83. function cleanup() {
  84. Person.remove(function() {
  85. mongoose.disconnect();
  86. });
  87. }