forked from Automattic/mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.js
2253 lines (1962 loc) · 61.1 KB
/
model.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Module dependencies.
*/
var Document = require('./document')
, MongooseArray = require('./types/array')
, MongooseBuffer = require('./types/buffer')
, MongooseError = require('./error')
, VersionError = MongooseError.VersionError
, DivergentArrayError = MongooseError.DivergentArrayError
, Query = require('./query')
, Aggregate = require('./aggregate')
, Schema = require('./schema')
, Types = require('./schema/index')
, utils = require('./utils')
, hasOwnProperty = utils.object.hasOwnProperty
, isMongooseObject = utils.isMongooseObject
, EventEmitter = require('events').EventEmitter
, merge = utils.merge
, Promise = require('./promise')
, assert = require('assert')
, util = require('util')
, tick = utils.tick
var VERSION_WHERE = 1
, VERSION_INC = 2
, VERSION_ALL = VERSION_WHERE | VERSION_INC;
/**
* Model constructor
*
* @param {Object} doc values to with which to create the document
* @inherits Document
* @event `error`: If listening to this Model event, it is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model.
* @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event.
* @api public
*/
function Model (doc, fields, skipId) {
Document.call(this, doc, fields, skipId);
};
/*!
* Inherits from Document.
*
* All Model.prototype features are available on
* top level (non-sub) documents.
*/
Model.prototype.__proto__ = Document.prototype;
/**
* Connection the model uses.
*
* @api public
* @property db
*/
Model.prototype.db;
/**
* Collection the model uses.
*
* @api public
* @property collection
*/
Model.prototype.collection;
/**
* The name of the model
*
* @api public
* @property modelName
*/
Model.prototype.modelName;
/*!
* Handles doc.save() callbacks
*/
function handleSave (promise, self) {
return tick(function handleSave (err, result) {
if (err) {
// If the initial insert fails provide a second chance.
// (If we did this all the time we would break updates)
if (self.$__.inserting) {
self.isNew = true;
self.emit('isNew', true);
}
promise.error(err);
promise = self = null;
return;
}
self.$__storeShard();
var numAffected;
if (result) {
// when inserting, the array of created docs is returned
numAffected = result.length
? result.length
: result;
} else {
numAffected = 0;
}
// was this an update that required a version bump?
if (self.$__.version && !self.$__.inserting) {
var doIncrement = VERSION_INC === (VERSION_INC & self.$__.version);
self.$__.version = undefined;
// increment version if was successful
if (numAffected > 0) {
if (doIncrement) {
var key = self.schema.options.versionKey;
var version = self.getValue(key) | 0;
self.setValue(key, version + 1);
}
} else {
// the update failed. pass an error back
promise.error(new VersionError);
promise = self = null;
return;
}
}
self.emit('save', self, numAffected);
promise.complete(self, numAffected);
promise = self = null;
});
}
/**
* Saves this document.
*
* ####Example:
*
* product.sold = Date.now();
* product.save(function (err, product) {
* if (err) ..
* })
*
* The `fn` callback is optional. If no `fn` is passed and validation fails, the validation error will be emitted on the connection used to create this model.
*
* var db = mongoose.createConnection(..);
* var schema = new Schema(..);
* var Product = db.model('Product', schema);
*
* db.on('error', handleError);
*
* However, if you desire more local error handling you can add an `error` listener to the model and handle errors there instead.
*
* Product.on('error', handleError);
*
* @param {Function} [fn] optional callback
* @api public
* @see middleware http://mongoosejs.com/docs/middleware.html
*/
Model.prototype.save = function save (fn) {
var promise = new Promise(fn)
, complete = handleSave(promise, this)
, options = {}
if (this.schema.options.safe) {
options.safe = this.schema.options.safe;
}
if (this.isNew) {
// send entire doc
var obj = this.toObject({ depopulate: 1, isParent: 1 });
this.$__version(true, obj);
this.collection.insert(obj, options, complete);
this.$__reset();
this.isNew = false;
this.emit('isNew', false);
// Make it possible to retry the insert
this.$__.inserting = true;
} else {
// Make sure we don't treat it as a new object on error,
// since it already exists
this.$__.inserting = false;
var delta = this.$__delta();
if (delta) {
if (delta instanceof Error) return complete(delta);
var where = this.$__where(delta[0]);
this.$__reset();
this.collection.update(where, delta[1], options, complete);
} else {
this.$__reset();
complete(null);
}
this.emit('isNew', false);
}
};
/*!
* Apply the operation to the delta (update) clause as
* well as track versioning for our where clause.
*
* @param {Document} self
* @param {Object} where
* @param {Object} delta
* @param {Object} data
* @param {Mixed} val
* @param {String} [operation]
*/
function operand (self, where, delta, data, val, op) {
// delta
op || (op = '$set');
if (!delta[op]) delta[op] = {};
delta[op][data.path] = val;
// disabled versioning?
if (false === self.schema.options.versionKey) return;
// already marked for versioning?
if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return;
switch (op) {
case '$set':
case '$unset':
case '$pop':
case '$pull':
case '$pullAll':
case '$push':
case '$pushAll':
case '$addToSet':
break;
default:
// nothing to do
return;
}
// ensure updates sent with positional notation are
// editing the correct array element.
// only increment the version if an array position changes.
// modifying elements of an array is ok if position does not change.
if ('$push' == op || '$pushAll' == op || '$addToSet' == op) {
self.$__.version = VERSION_INC;
}
else if (/^\$p/.test(op)) {
// potentially changing array positions
self.increment();
}
else if (Array.isArray(val)) {
// $set an array
self.increment();
}
// now handling $set, $unset
else if (/\.\d+\.|\.\d+$/.test(data.path)) {
// subpath of array
self.$__.version = VERSION_WHERE;
}
}
/*!
* Compiles an update and where clause for a `val` with _atomics.
*
* @param {Document} self
* @param {Object} where
* @param {Object} delta
* @param {Object} data
* @param {Array} value
*/
function handleAtomics (self, where, delta, data, value) {
if (delta.$set && delta.$set[data.path]) {
// $set has precedence over other atomics
return;
}
if ('function' == typeof value.$__getAtomics) {
value.$__getAtomics().forEach(function (atomic) {
var op = atomic[0];
var val = atomic[1];
operand(self, where, delta, data, val, op);
})
return;
}
// legacy support for plugins
var atomics = value._atomics
, ops = Object.keys(atomics)
, i = ops.length
, val
, op;
if (0 === i) {
// $set
if (isMongooseObject(value)) {
value = value.toObject({ depopulate: 1 });
} else if (value.valueOf) {
value = value.valueOf();
}
return operand(self, where, delta, data, value);
}
while (i--) {
op = ops[i];
val = atomics[op];
if (isMongooseObject(val)) {
val = val.toObject({ depopulate: 1 })
} else if (Array.isArray(val)) {
val = val.map(function (mem) {
return isMongooseObject(mem)
? mem.toObject({ depopulate: 1 })
: mem;
})
} else if (val.valueOf) {
val = val.valueOf()
}
if ('$addToSet' === op)
val = { $each: val };
operand(self, where, delta, data, val, op);
}
}
/**
* Produces a special query document of the modified properties used in updates.
*
* @api private
* @method $__delta
* @memberOf Model
*/
Model.prototype.$__delta = function () {
var dirty = this.$__dirty();
if (!dirty.length) return;
var where = {}
, delta = {}
, len = dirty.length
, divergent = []
, d = 0
, val
, obj
for (; d < len; ++d) {
var data = dirty[d]
var value = data.value
var schema = data.schema
var match = checkDivergentArray(this, data.path, value);
if (match) {
divergent.push(match);
continue;
}
if (divergent.length) continue;
if (undefined === value) {
operand(this, where, delta, data, 1, '$unset');
} else if (null === value) {
operand(this, where, delta, data, null);
} else if (value._path && value._atomics) {
// arrays and other custom types (support plugins etc)
handleAtomics(this, where, delta, data, value);
} else if (value._path && Buffer.isBuffer(value)) {
// MongooseBuffer
value = value.toObject();
operand(this, where, delta, data, value);
} else {
value = utils.clone(value, { depopulate: 1 });
operand(this, where, delta, data, value);
}
}
if (divergent.length) {
return new DivergentArrayError(divergent);
}
if (this.$__.version) {
this.$__version(where, delta);
}
return [where, delta];
}
/*!
* Determine if array was populated with some form of filter and is now
* being updated in a manner which could overwrite data unintentionally.
*
* @see https://github.com/LearnBoost/mongoose/issues/1334
* @param {Document} doc
* @param {String} path
* @return {String|undefined}
*/
function checkDivergentArray (doc, path, array) {
// see if we populated this path
var pop = doc.populated(path, true);
if (!pop && doc.$__.selected) {
// If any array was selected using an $elemMatch projection, we deny the update.
// NOTE: MongoDB only supports projected $elemMatch on top level array.
var top = path.split('.')[0];
if (doc.$__.selected[top] && doc.$__.selected[top].$elemMatch) {
return top;
}
}
if (!(pop && array instanceof MongooseArray)) return;
// If the array was populated using options that prevented all
// documents from being returned (match, skip, limit) or they
// deselected the _id field, $pop and $set of the array are
// not safe operations. If _id was deselected, we do not know
// how to remove elements. $pop will pop off the _id from the end
// of the array in the db which is not guaranteed to be the
// same as the last element we have here. $set of the entire array
// would be similarily destructive as we never received all
// elements of the array and potentially would overwrite data.
var check = pop.options.match ||
pop.options.options && hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted
pop.options.options && pop.options.options.skip || // 0 is permitted
pop.options.select && // deselected _id?
(0 === pop.options.select._id ||
/\s?-_id\s?/.test(pop.options.select))
if (check) {
var atomics = array._atomics;
if (0 === Object.keys(atomics).length || atomics.$set || atomics.$pop) {
return path;
}
}
}
/**
* Appends versioning to the where and update clauses.
*
* @api private
* @method $__version
* @memberOf Model
*/
Model.prototype.$__version = function (where, delta) {
var key = this.schema.options.versionKey;
if (true === where) {
// this is an insert
if (key) this.setValue(key, delta[key] = 0);
return;
}
// updates
// only apply versioning if our versionKey was selected. else
// there is no way to select the correct version. we could fail
// fast here and force them to include the versionKey but
// thats a bit intrusive. can we do this automatically?
if (!this.isSelected(key)) {
return;
}
// $push $addToSet don't need the where clause set
if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) {
where[key] = this.getValue(key);
}
if (VERSION_INC === (VERSION_INC & this.$__.version)) {
delta.$inc || (delta.$inc = {});
delta.$inc[key] = 1;
}
}
/**
* Signal that we desire an increment of this documents version.
*
* @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey
* @api public
*/
Model.prototype.increment = function increment () {
this.$__.version = VERSION_ALL;
return this;
}
/**
* Returns a query object which applies shardkeys if they exist.
*
* @api private
* @method $__where
* @memberOf Model
*/
Model.prototype.$__where = function _where (where) {
where || (where = {});
var paths
, len
if (this.$__.shardval) {
paths = Object.keys(this.$__.shardval)
len = paths.length
for (var i = 0; i < len; ++i) {
where[paths[i]] = this.$__.shardval[paths[i]];
}
}
where._id = this._doc._id;
return where;
}
/**
* Removes this document from the db.
*
* ####Example:
*
* product.remove(function (err, product) {
* if (err) return handleError(err);
* Product.findById(product._id, function (err, product) {
* console.log(product) // null
* })
* })
*
* @param {Function} [fn] optional callback
* @api public
*/
Model.prototype.remove = function remove (fn) {
if (this.$__.removing) {
this.$__.removing.addBack(fn);
return this;
}
var promise = this.$__.removing = new Promise(fn)
, where = this.$__where()
, self = this
, options = {}
if (this.schema.options.safe) {
options.safe = this.schema.options.safe;
}
this.collection.remove(where, options, tick(function (err) {
if (err) {
promise.error(err);
promise = self = self.$__.removing = where = options = null;
return;
}
self.emit('remove', self);
promise.complete(self);
promise = self = where = options = null;
}));
return this;
};
/**
* Returns another Model instance.
*
* ####Example:
*
* var doc = new Tank;
* doc.model('User').findById(id, callback);
*
* @param {String} name model name
* @api public
*/
Model.prototype.model = function model (name) {
return this.db.model(name);
};
// Model (class) features
/*!
* Give the constructor the ability to emit events.
*/
for (var i in EventEmitter.prototype)
Model[i] = EventEmitter.prototype[i];
/**
* Called when the model compiles.
*
* @api private
*/
Model.init = function init () {
if (this.schema.options.autoIndex) {
this.ensureIndexes();
}
this.schema.emit('init', this);
};
/**
* Sends `ensureIndex` commands to mongo for each index declared in the schema.
*
* ####Example:
*
* Event.ensureIndexes(function (err) {
* if (err) return handleError(err);
* });
*
* After completion, an `index` event is emitted on this `Model` passing an error if one occurred.
*
* ####Example:
*
* var eventSchema = new Schema({ thing: { type: 'string', unique: true }})
* var Event = mongoose.model('Event', eventSchema);
*
* Event.on('index', function (err) {
* if (err) console.error(err); // error occurred during index creation
* })
*
* _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._
*
* The `ensureIndex` commands are not sent in parallel. This is to avoid the `MongoError: cannot add index with a background operation in progress` error. See [this ticket](https://github.com/LearnBoost/mongoose/issues/1365) for more information.
*
* @param {Function} [cb] optional callback
* @api public
*/
Model.ensureIndexes = function ensureIndexes (cb) {
var indexes = this.schema.indexes();
if (!indexes.length) {
return cb && process.nextTick(cb);
}
// Indexes are created one-by-one to support how MongoDB < 2.4 deals
// with background indexes.
var self = this
, safe = self.schema.options.safe
function done (err) {
self.emit('index', err);
cb && cb(err);
}
function create () {
var index = indexes.shift();
if (!index) return done();
var options = index[1];
options.safe = safe;
self.collection.ensureIndex(index[0], options, tick(function (err) {
if (err) return done(err);
create();
}));
}
create();
}
/**
* Schema the model uses.
*
* @property schema
* @receiver Model
* @api public
*/
Model.schema;
/*!
* Connection instance the model uses.
*
* @property db
* @receiver Model
* @api public
*/
Model.db;
/*!
* Collection the model uses.
*
* @property collection
* @receiver Model
* @api public
*/
Model.collection;
/**
* Base Mongoose instance the model uses.
*
* @property base
* @receiver Model
* @api public
*/
Model.base;
/**
* Removes documents from the collection.
*
* ####Example:
*
* Comment.remove({ title: 'baby born from alien father' }, function (err) {
*
* });
*
* ####Note:
*
* To remove documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js):
*
* var query = Comment.remove({ _id: id });
* query.exec();
*
* ####Note:
*
* This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, _no middleware (hooks) are executed_.
*
* @param {Object} conditions
* @param {Function} [callback]
* @return {Query}
* @api public
*/
Model.remove = function remove (conditions, callback) {
if ('function' === typeof conditions) {
callback = conditions;
conditions = {};
}
var query = new Query(conditions).bind(this, 'remove');
if ('undefined' === typeof callback)
return query;
this._applyNamedScope(query);
return query.remove(callback);
};
/**
* Finds documents
*
* The `conditions` are cast to their respective SchemaTypes before the command is sent.
*
* ####Examples:
*
* // named john and at least 18
* MyModel.find({ name: 'john', age: { $gte: 18 }});
*
* // executes immediately, passing results to callback
* MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
*
* // name LIKE john and only selecting the "name" and "friends" fields, executing immediately
* MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })
*
* // passing options
* MyModel.find({ name: /john/i }, null, { skip: 10 })
*
* // passing options and executing immediately
* MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});
*
* // executing a query explicitly
* var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
* query.exec(function (err, docs) {});
*
* // using the promise returned from executing a query
* var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
* var promise = query.exec();
* promise.addBack(function (err, docs) {});
*
* @param {Object} conditions
* @param {Object} [fields] optional fields to select
* @param {Object} [options] optional
* @param {Function} [callback]
* @return {Query}
* @see field selection #query_Query-select
* @see promise #promise-js
* @api public
*/
Model.find = function find (conditions, fields, options, callback) {
if ('function' == typeof conditions) {
callback = conditions;
conditions = {};
fields = null;
options = null;
} else if ('function' == typeof fields) {
callback = fields;
fields = null;
options = null;
} else if ('function' == typeof options) {
callback = options;
options = null;
}
var query = new Query(conditions, options);
query.bind(this, 'find');
query.select(fields);
if ('undefined' === typeof callback)
return query;
this._applyNamedScope(query);
return query.find(callback);
};
/**
* Merges the current named scope query into `query`.
*
* @param {Query} query
* @return {Query}
* @api private
*/
Model._applyNamedScope = function _applyNamedScope (query) {
var cQuery = this._cumulativeQuery;
if (cQuery) {
merge(query._conditions, cQuery._conditions);
if (query._fields && cQuery._fields)
merge(query._fields, cQuery._fields);
if (query.options && cQuery.options)
merge(query.options, cQuery.options);
delete this._cumulativeQuery;
}
return query;
}
/**
* Finds a single document by id.
*
* The `id` is cast based on the Schema before sending the command.
*
* ####Example:
*
* // find adventure by id and execute immediately
* Adventure.findById(id, function (err, adventure) {});
*
* // same as above
* Adventure.findById(id).exec(callback);
*
* // select only the adventures name and length
* Adventure.findById(id, 'name length', function (err, adventure) {});
*
* // same as above
* Adventure.findById(id, 'name length').exec(callback);
*
* // include all properties except for `length`
* Adventure.findById(id, '-length').exec(function (err, adventure) {});
*
* // passing options (in this case return the raw js objects, not mongoose documents by passing `lean`
* Adventure.findById(id, 'name', { lean: true }, function (err, doc) {});
*
* // same as above
* Adventure.findById(id, 'name').lean().exec(function (err, doc) {});
*
* @param {ObjectId|HexId} id objectid, or a value that can be casted to one
* @param {Object} [fields] optional fields to select
* @param {Object} [options] optional
* @param {Function} [callback]
* @return {Query}
* @see field selection #query_Query-select
* @see lean queries #query_Query-lean
* @api public
*/
Model.findById = function findById (id, fields, options, callback) {
return this.findOne({ _id: id }, fields, options, callback);
};
/**
* Finds one document.
*
* The `conditions` are cast to their respective SchemaTypes before the command is sent.
*
* ####Example:
*
* // find one iphone adventures - iphone adventures??
* Adventure.findOne({ type: 'iphone' }, function (err, adventure) {});
*
* // same as above
* Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {});
*
* // select only the adventures name
* Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {});
*
* // same as above
* Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {});
*
* // specify options, in this case lean
* Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback);
*
* // same as above
* Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback);
*
* // chaining findOne queries (same as above)
* Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback);
*
* @param {Object} conditions
* @param {Object} [fields] optional fields to select
* @param {Object} [options] optional
* @param {Function} [callback]
* @return {Query}
* @see field selection #query_Query-select
* @see lean queries #query_Query-lean
* @api public
*/
Model.findOne = function findOne (conditions, fields, options, callback) {
if ('function' == typeof options) {
callback = options;
options = null;
} else if ('function' == typeof fields) {
callback = fields;
fields = null;
options = null;
} else if ('function' == typeof conditions) {
callback = conditions;
conditions = {};
fields = null;
options = null;
}
var query = new Query(conditions, options).select(fields).bind(this, 'findOne');
if ('undefined' == typeof callback)
return query;
this._applyNamedScope(query);
return query.findOne(callback);
};
/**
* Counts number of matching documents in a database collection.
*
* ####Example:
*
* Adventure.count({ type: 'jungle' }, function (err, count) {
* if (err) ..
* console.log('there are %d jungle adventures', count);
* });
*
* @param {Object} conditions
* @param {Function} [callback]
* @return {Query}
* @api public
*/
Model.count = function count (conditions, callback) {
if ('function' === typeof conditions)
callback = conditions, conditions = {};
var query = new Query(conditions).bind(this, 'count');
if ('undefined' == typeof callback)
return query;
this._applyNamedScope(query);
return query.count(callback);
};
/**
* Executes a DISTINCT command
*
* @param {String} field
* @param {Object} [conditions] optional
* @param {Function} [callback]
* @return {Query}
* @api public
*/
Model.distinct = function distinct (field, conditions, callback) {
var query = new Query(conditions).bind(this, 'distinct');
if ('undefined' == typeof callback) {
query._distinctArg = field;
return query;
}
this._applyNamedScope(query);
return query.distinct(field, callback);
};
/**
* Creates a Query, applies the passed conditions, and returns the Query.
*
* For example, instead of writing:
*
* User.find({age: {$gte: 21, $lte: 65}}, callback);
*
* we can instead write:
*
* User.where('age').gte(21).lte(65).exec(callback);