thoughts/node_modules/mongoose/examples/promises/promise.js
node_modules/mongoose/examples/promises/promise.jsRaw
1// import async to make control flow simplier
2var async = require('async');
3
4// import the rest of the normal stuff
5var mongoose = require('../../lib');
6
7require('./person.js')();
8
9var Person = mongoose.model('Person');
10
11// define some dummy data
12var data = [
13 {
14 name: 'bill',
15 age: 25,
16 birthday: new Date().setFullYear((new Date().getFullYear() - 25))
17 },
18 {
19 name: 'mary',
20 age: 30,
21 birthday: new Date().setFullYear((new Date().getFullYear() - 30))
22 },
23 {
24 name: 'bob',
25 age: 21,
26 birthday: new Date().setFullYear((new Date().getFullYear() - 21))
27 },
28 {
29 name: 'lilly',
30 age: 26,
31 birthday: new Date().setFullYear((new Date().getFullYear() - 26))
32 },
33 {
34 name: 'alucard',
35 age: 1000,
36 birthday: new Date().setFullYear((new Date().getFullYear() - 1000))
37 }
38];
39
40
41mongoose.connect('mongodb://localhost/persons', function(err) {
42 if (err) {
43 throw err;
44 }
45
46 // create all of the dummy people
47 async.each(data, function(item, cb) {
48 Person.create(item, cb);
49 }, function(err) {
50 if (err) {
51 // handle error
52 }
53
54 // create a promise (get one from the query builder)
55 var prom = Person.find({age: {$lt: 1000}}).exec();
56
57 // add a callback on the promise. This will be called on both error and
58 // complete
59 prom.addBack(function() {
60 console.log('completed');
61 });
62
63 // add a callback that is only called on complete (success) events
64 prom.addCallback(function() {
65 console.log('Successful Completion!');
66 });
67
68 // add a callback that is only called on err (rejected) events
69 prom.addErrback(function() {
70 console.log('Fail Boat');
71 });
72
73 // you can chain things just like in the promise/A+ spec
74 // note: each then() is returning a new promise, so the above methods
75 // that we defined will all fire after the initial promise is fulfilled
76 prom.then(function(people) {
77 // just getting the stuff for the next query
78 var ids = people.map(function(p) {
79 return p._id;
80 });
81
82 // return the next promise
83 return Person.find({_id: {$nin: ids}}).exec();
84 }).then(function(oldest) {
85 console.log('Oldest person is: %s', oldest);
86 }).then(cleanup);
87 });
88});
89
90function cleanup() {
91 Person.remove(function() {
92 mongoose.disconnect();
93 });
94}