gs_example.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. var mongoose = require('../../lib');
  2. // import the global schema, this can be done in any file that needs the model
  3. require('./person.js')();
  4. // grab the person model object
  5. var Person = mongoose.model('Person');
  6. // connect to a server to do a quick write / read example
  7. mongoose.connect('mongodb://localhost/persons', function(err) {
  8. if (err) {
  9. throw err;
  10. }
  11. Person.create({
  12. name: 'bill',
  13. age: 25,
  14. birthday: new Date().setFullYear((new Date().getFullYear() - 25))
  15. }, function(err, bill) {
  16. if (err) {
  17. throw err;
  18. }
  19. console.log('People added to db: %s', bill.toString());
  20. Person.find({}, function(err, people) {
  21. if (err) {
  22. throw err;
  23. }
  24. people.forEach(function(person) {
  25. console.log('People in the db: %s', person.toString());
  26. });
  27. // make sure to clean things up after we're done
  28. setTimeout(function() {
  29. cleanup();
  30. }, 2000);
  31. });
  32. });
  33. });
  34. function cleanup() {
  35. Person.remove(function() {
  36. mongoose.disconnect();
  37. });
  38. }