thoughts/node_modules/mongoose/examples/lean/lean.js
node_modules/mongoose/examples/lean/lean.jsRaw
1
2// import async to make control flow simplier
3var async = require('async');
4
5// import the rest of the normal stuff
6var mongoose = require('../../lib');
7
8require('./person.js')();
9
10var Person = mongoose.model('Person');
11
12// define some dummy data
13var data = [
14 {
15 name: 'bill',
16 age: 25,
17 birthday: new Date().setFullYear((new Date().getFullYear() - 25)),
18 gender: 'Male',
19 likes: ['movies', 'games', 'dogs']
20 },
21 {
22 name: 'mary',
23 age: 30,
24 birthday: new Date().setFullYear((new Date().getFullYear() - 30)),
25 gender: 'Female',
26 likes: ['movies', 'birds', 'cats']
27 },
28 {
29 name: 'bob',
30 age: 21,
31 birthday: new Date().setFullYear((new Date().getFullYear() - 21)),
32 gender: 'Male',
33 likes: ['tv', 'games', 'rabbits']
34 },
35 {
36 name: 'lilly',
37 age: 26,
38 birthday: new Date().setFullYear((new Date().getFullYear() - 26)),
39 gender: 'Female',
40 likes: ['books', 'cats', 'dogs']
41 },
42 {
43 name: 'alucard',
44 age: 1000,
45 birthday: new Date().setFullYear((new Date().getFullYear() - 1000)),
46 gender: 'Male',
47 likes: ['glasses', 'wine', 'the night']
48 }
49];
50
51
52mongoose.connect('mongodb://localhost/persons', function(err) {
53 if (err) throw err;
54
55 // create all of the dummy people
56 async.each(data, function(item, cb) {
57 Person.create(item, cb);
58 }, function(err) {
59 if (err) {
60 // handle error
61 }
62
63 // lean queries return just plain javascript objects, not
64 // MongooseDocuments. This makes them good for high performance read
65 // situations
66
67 // when using .lean() the default is true, but you can explicitly set the
68 // value by passing in a boolean value. IE. .lean(false)
69 var q = Person.find({age: {$lt: 1000}}).sort('age').limit(2).lean();
70 q.exec(function(err, results) {
71 if (err) throw err;
72 console.log('Are the results MongooseDocuments?: %s', results[0] instanceof mongoose.Document);
73
74 console.log(results);
75 cleanup();
76 });
77 });
78});
79
80function cleanup() {
81 Person.remove(function() {
82 mongoose.disconnect();
83 });
84}