UNPKG

2.58 kBJavaScriptView Raw
1// mongoose-long
2
3module.exports = exports = function NumberLong (mongoose) {
4 var Schema = mongoose.Schema
5 , SchemaType = mongoose.SchemaType
6 , Types = mongoose.Types
7 , mongo = mongoose.mongo;
8
9 /**
10 * Long constructor
11 *
12 * @inherits SchemaType
13 * @param {String} key
14 * @param {Object} [options]
15 */
16
17 function Long (key, options) {
18 SchemaType.call(this, key, options);
19 }
20
21 /*!
22 * inherits
23 */
24
25 Long.prototype.__proto__ = SchemaType.prototype;
26
27 /**
28 * Implement checkRequired method.
29 *
30 * @param {any} val
31 * @return {Boolean}
32 */
33
34 Long.prototype.checkRequired = function (val) {
35 return null != val;
36 }
37
38 /**
39 * Implement casting.
40 *
41 * @param {any} val
42 * @param {Object} [scope]
43 * @param {Boolean} [init]
44 * @return {mongo.Long|null}
45 */
46
47 Long.prototype.cast = function (val, scope, init) {
48 if (null === val) return val;
49 if ('' === val) return null;
50
51 if (val instanceof mongo.Long)
52 return val;
53
54 if (val instanceof Number || 'number' == typeof val)
55 return mongo.Long.fromNumber(val);
56
57 if (!Array.isArray(val) && val.toString)
58 return mongo.Long.fromString(val.toString());
59
60 throw new SchemaType.CastError('Long', val)
61 }
62
63 /*!
64 * ignore
65 */
66
67 function handleSingle (val) {
68 return this.cast(val)
69 }
70
71 function handleArray (val) {
72 var self = this;
73 return val.map( function (m) {
74 return self.cast(m)
75 });
76 }
77
78 Long.prototype.$conditionalHandlers.$lt = handleSingle;
79 Long.prototype.$conditionalHandlers.$lte = handleSingle;
80 Long.prototype.$conditionalHandlers.$gt = handleSingle;
81 Long.prototype.$conditionalHandlers.$gte = handleSingle;
82 Long.prototype.$conditionalHandlers.$ne = handleSingle;
83 Long.prototype.$conditionalHandlers.$in = handleArray;
84 Long.prototype.$conditionalHandlers.$nin = handleArray;
85 Long.prototype.$conditionalHandlers.$mod = handleArray;
86 Long.prototype.$conditionalHandlers.$all = handleArray;
87
88 /**
89 * Implement query casting, for mongoose 3.0
90 *
91 * @param {String} $conditional
92 * @param {*} [value]
93 */
94
95 Long.prototype.castForQuery = function ($conditional, value) {
96 var handler;
97 if (2 === arguments.length) {
98 handler = this.$conditionalHandlers[$conditional];
99 if (!handler) {
100 throw new Error("Can't use " + $conditional + " with Long.");
101 }
102 return handler.call(this, value);
103 } else {
104 return this.cast($conditional);
105 }
106 }
107
108 /**
109 * Expose
110 */
111
112 Schema.Types.Long = Long;
113 Types.Long = mongo.Long;
114 return Long;
115}
116