blackhole.db 2.0.2 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/collection.js +299 -0
- package/document.js +476 -0
- package/index.js +191 -215
- package/lib/engine.js +861 -0
- package/lib/errors.js +94 -0
- package/lib/objectid.js +50 -0
- package/lib/schema.js +555 -0
- package/model.js +260 -0
- package/package.json +1 -1
- package/query.js +551 -0
package/query.js
ADDED
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const engine = require('./engine');
|
|
3
|
+
const ObjectId = require('./objectid');
|
|
4
|
+
const S = require('./schema');
|
|
5
|
+
const { runHooks, runErrorHooks } = require('./document');
|
|
6
|
+
const { CastError, ValidationError, DocumentNotFoundError, ObjectParameterError } = require('./errors');
|
|
7
|
+
|
|
8
|
+
const { isObj, isOpObject, clone } = engine;
|
|
9
|
+
const POSITIONAL = /\$\[[^\]]*\]/g;
|
|
10
|
+
|
|
11
|
+
// ---------- casting of filters and updates ----------
|
|
12
|
+
function nodeFor(schema, path) { return schema.path(path.replace(POSITIONAL, '$')); }
|
|
13
|
+
|
|
14
|
+
function castOne(node, x, path) {
|
|
15
|
+
if (x === null || x === undefined || x instanceof RegExp) return x;
|
|
16
|
+
if (node.kind === 'Mixed') return x;
|
|
17
|
+
if (node.kind === 'Array') return Array.isArray(x) ? S.castValue(node, x, path) : castOne(node.of, x, path);
|
|
18
|
+
if (node.kind === 'Embedded') return x;
|
|
19
|
+
if (node.kind === 'String' && typeof x === 'object' && !(x instanceof ObjectId)) return x;
|
|
20
|
+
return S.castValue(node, x, path);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// cast for writes: subdocuments get defaults and ids
|
|
24
|
+
function cw(node, x, path) { return x === null || x === undefined ? x : node.kind === 'Embedded' || node.kind === 'Array' ? S.castValue(node, x, path) : castOne(node, x, path); }
|
|
25
|
+
|
|
26
|
+
function castCond(node, cond, path) {
|
|
27
|
+
if (cond === null || cond === undefined || cond instanceof RegExp) return cond;
|
|
28
|
+
if (isOpObject(cond)) {
|
|
29
|
+
const out = {};
|
|
30
|
+
for (const op of Object.keys(cond)) {
|
|
31
|
+
const a = cond[op];
|
|
32
|
+
switch (op) {
|
|
33
|
+
case '$eq': case '$ne': case '$gt': case '$gte': case '$lt': case '$lte': out[op] = castOne(node, a, path); break;
|
|
34
|
+
case '$in': case '$nin': out[op] = Array.isArray(a) ? a.map((x) => castOne(node.kind === 'Array' ? node.of : node, x, path)) : a; break;
|
|
35
|
+
case '$all': out[op] = Array.isArray(a) ? a.map((x) => (isObj(x) && x.$elemMatch ? x : castOne(node.kind === 'Array' ? node.of : node, x, path))) : a; break;
|
|
36
|
+
case '$not': out[op] = castCond(node, a, path); break;
|
|
37
|
+
case '$elemMatch':
|
|
38
|
+
if (node.kind === 'Array' && node.of.kind === 'Embedded') out[op] = castFilter(node.of.schema, a);
|
|
39
|
+
else if (node.kind === 'Array' && isOpObject(a)) out[op] = castCond(node.of, a, path);
|
|
40
|
+
else out[op] = a;
|
|
41
|
+
break;
|
|
42
|
+
default: out[op] = a;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
return castOne(node, cond, path);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function castFilter(schema, filter) {
|
|
51
|
+
if (filter === undefined || filter === null) return {};
|
|
52
|
+
if (!isObj(filter)) throw new ObjectParameterError(filter, 'filter', 'find');
|
|
53
|
+
const out = {};
|
|
54
|
+
for (const key of Object.keys(filter)) {
|
|
55
|
+
const v = filter[key];
|
|
56
|
+
if (key === '$and' || key === '$or' || key === '$nor') out[key] = v.map((x) => castFilter(schema, x));
|
|
57
|
+
else if (key[0] === '$') out[key] = v;
|
|
58
|
+
else {
|
|
59
|
+
const node = nodeFor(schema, key);
|
|
60
|
+
out[key] = node ? castCond(node, v, key) : v;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function castUpdate(schema, update, options = {}) {
|
|
67
|
+
if (!isObj(update)) throw new ObjectParameterError(update, 'update', 'update');
|
|
68
|
+
const ops = {};
|
|
69
|
+
const bare = {};
|
|
70
|
+
for (const k of Object.keys(update)) { if (k[0] === '$') ops[k] = update[k]; else bare[k] = update[k]; }
|
|
71
|
+
if (Object.keys(bare).length) ops.$set = { ...(ops.$set || {}), ...bare };
|
|
72
|
+
const strict = options.strict === undefined ? schema.options.strict : options.strict;
|
|
73
|
+
const out = {};
|
|
74
|
+
const keep = (path) => {
|
|
75
|
+
if (nodeFor(schema, path) || schema.nested[path] || path === '_id' || path === schema.options.versionKey) return true;
|
|
76
|
+
const root = path.split('.')[0];
|
|
77
|
+
for (let i = path.split('.').length; i > 0; i--) { const n = schema.paths[path.split('.').slice(0, i).join('.')]; if (n && (n.kind === 'Mixed' || n.kind === 'Map')) return true; }
|
|
78
|
+
if (schema.nested[root] || Object.keys(schema.paths).some((p) => p.startsWith(`${path}.`))) return true;
|
|
79
|
+
if (strict === 'throw') throw new (require('./errors').StrictModeError)(path);
|
|
80
|
+
return strict === false;
|
|
81
|
+
};
|
|
82
|
+
for (const op of Object.keys(ops)) {
|
|
83
|
+
const spec = ops[op];
|
|
84
|
+
if (!isObj(spec) && op !== '$unset') throw new Error(`Invalid atomic update value for ${op}. Expected an object, received ${typeof spec}`);
|
|
85
|
+
const res = {};
|
|
86
|
+
for (const path of Object.keys(spec)) {
|
|
87
|
+
if (!keep(path)) continue;
|
|
88
|
+
const node = nodeFor(schema, path);
|
|
89
|
+
const v = spec[path];
|
|
90
|
+
switch (op) {
|
|
91
|
+
case '$set': case '$setOnInsert': case '$min': case '$max': {
|
|
92
|
+
if (v === undefined) break;
|
|
93
|
+
if (node) {
|
|
94
|
+
const cast = path in schema.paths ? S.applySetters(node, v, path, {}) : (node.kind === 'Mixed' ? v : cw(node, v, path));
|
|
95
|
+
if (path === '_id' || (node.opts.immutable && op === '$set')) { if (path !== '_id') continue; }
|
|
96
|
+
res[path] = cast;
|
|
97
|
+
} else if (schema.nested[path] && isObj(v)) {
|
|
98
|
+
const walk = (p, val) => {
|
|
99
|
+
const n = schema.paths[p];
|
|
100
|
+
if (n) res[p] = S.applySetters(n, val, p, {});
|
|
101
|
+
else if (schema.nested[p] && isObj(val)) for (const k of Object.keys(val)) walk(`${p}.${k}`, val[k]);
|
|
102
|
+
};
|
|
103
|
+
walk(path, v);
|
|
104
|
+
} else res[path] = v;
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
107
|
+
case '$inc': case '$mul': res[path] = node && node.kind === 'Number' ? S.castLeaf(node, v, path) : (typeof v === 'string' && !Number.isNaN(Number(v)) ? Number(v) : v); break;
|
|
108
|
+
case '$push': case '$addToSet': {
|
|
109
|
+
const el = node && node.kind === 'Array' ? node.of : null;
|
|
110
|
+
const c = (x) => (el && el.kind !== 'Mixed' ? cw(el, x, path) : x);
|
|
111
|
+
if (isObj(v) && '$each' in v) res[path] = { ...v, $each: v.$each.map(c) };
|
|
112
|
+
else res[path] = c(v);
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
case '$pull': {
|
|
116
|
+
const el = node && node.kind === 'Array' ? node.of : null;
|
|
117
|
+
if (el && el.kind === 'Embedded' && isObj(v)) res[path] = castFilter(el.schema, v);
|
|
118
|
+
else if (el && isOpObject(v)) res[path] = castCond(el, v, path);
|
|
119
|
+
else if (el && el.kind !== 'Mixed') res[path] = castOne(el, v, path);
|
|
120
|
+
else res[path] = v;
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
case '$pullAll': { const el = node && node.kind === 'Array' ? node.of : null; res[path] = el && el.kind !== 'Mixed' ? v.map((x) => castOne(el, x, path)) : v; break; }
|
|
124
|
+
default: res[path] = v;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (op === '$unset' || Object.keys(res).length) out[op] = res;
|
|
128
|
+
}
|
|
129
|
+
// Update values must not alias objects owned by the caller (Mixed values pass through casting as-is).
|
|
130
|
+
for (const op of Object.keys(out)) out[op] = clone(out[op]);
|
|
131
|
+
// timestamps
|
|
132
|
+
const ts = schema.options.timestamps;
|
|
133
|
+
if (ts && options.timestamps !== false) {
|
|
134
|
+
const now = new Date();
|
|
135
|
+
if (ts.updatedAt) { out.$set = out.$set || {}; if (!(ts.updatedAt in out.$set)) out.$set[ts.updatedAt] = now; }
|
|
136
|
+
if (ts.createdAt) { out.$setOnInsert = out.$setOnInsert || {}; if (!(ts.createdAt in out.$setOnInsert) && !(out.$set && ts.createdAt in out.$set)) out.$setOnInsert[ts.createdAt] = now; }
|
|
137
|
+
}
|
|
138
|
+
if (schema.options.versionKey && !(out.$set && schema.options.versionKey in out.$set)) { out.$setOnInsert = out.$setOnInsert || {}; if (!(schema.options.versionKey in out.$setOnInsert)) out.$setOnInsert[schema.options.versionKey] = 0; }
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ---------- projection ----------
|
|
143
|
+
function effectiveProjection(schema, fields, force) {
|
|
144
|
+
let proj = engine.normalizeProjection(fields) || {};
|
|
145
|
+
const hidden = Object.keys(schema.paths).filter((p) => schema.paths[p].opts.select === false && !force.has(p) && !(p in proj));
|
|
146
|
+
if (!hidden.length) return Object.keys(proj).length ? proj : null;
|
|
147
|
+
const inclusion = Object.entries(proj).some(([k, v]) => k !== '_id' && !engine.isObj(v) && v);
|
|
148
|
+
if (inclusion) return proj;
|
|
149
|
+
proj = { ...proj };
|
|
150
|
+
for (const p of hidden) proj[p] = 0;
|
|
151
|
+
return proj;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ---------- populate ----------
|
|
155
|
+
function normalizePopulate(args) {
|
|
156
|
+
const out = [];
|
|
157
|
+
const add = (a) => {
|
|
158
|
+
if (a === undefined || a === null) return;
|
|
159
|
+
if (Array.isArray(a)) a.forEach(add);
|
|
160
|
+
else if (typeof a === 'string') for (const p of a.split(/\s+/).filter(Boolean)) out.push({ path: p });
|
|
161
|
+
else if (isObj(a)) out.push({ ...a });
|
|
162
|
+
};
|
|
163
|
+
args.forEach(add);
|
|
164
|
+
return out;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function populateResults(model, results, populate, lean) {
|
|
168
|
+
const docs = (Array.isArray(results) ? results : [results]).filter(Boolean);
|
|
169
|
+
if (!docs.length) return;
|
|
170
|
+
for (const opt of populate) await populateOne(model, docs, opt, lean);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function populateOne(model, docs, opt, lean) {
|
|
174
|
+
const schema = model.schema;
|
|
175
|
+
const path = opt.path;
|
|
176
|
+
const virtual = schema.virtuals[path];
|
|
177
|
+
const node = schema.path(path);
|
|
178
|
+
const refOf = (n) => (n && (n.opts.ref || (n.kind === 'Array' && n.of && n.of.opts.ref)));
|
|
179
|
+
let ref = opt.model || (virtual && virtual.options.ref) || refOf(node);
|
|
180
|
+
const dbm = model.db;
|
|
181
|
+
const read = (d, p) => (d.$isblackholeDocument ? d.$__.proxy.get(p) : engine.getPath(d, p));
|
|
182
|
+
const targetFor = (d) => {
|
|
183
|
+
let r = ref;
|
|
184
|
+
if (!r && node && node.opts.refPath) r = read(d, node.opts.refPath);
|
|
185
|
+
if (typeof r === 'function' && !r.modelName) r = r.call(d, d);
|
|
186
|
+
return typeof r === 'string' ? dbm.model(r) : r;
|
|
187
|
+
};
|
|
188
|
+
if (!ref && !(node && node.opts.refPath)) throw new Error(`Cannot populate path \`${path}\` because it is not in your schema. Set the \`strictPopulate\` option to false to override.`);
|
|
189
|
+
|
|
190
|
+
const foreignField = virtual ? virtual.options.foreignField : '_id';
|
|
191
|
+
const localField = virtual ? virtual.options.localField : path;
|
|
192
|
+
const byModel = new Map();
|
|
193
|
+
for (const d of docs) {
|
|
194
|
+
const target = targetFor(d);
|
|
195
|
+
if (!target) continue;
|
|
196
|
+
const local = virtual ? read(d, localField) : (d.$isblackholeDocument ? d._doc[path] : engine.getPath(d, path));
|
|
197
|
+
const vals = [].concat(local === undefined || local === null ? [] : local).filter((v) => v !== null && v !== undefined);
|
|
198
|
+
let entry = byModel.get(target);
|
|
199
|
+
if (!entry) byModel.set(target, entry = { ids: [], docs: [] });
|
|
200
|
+
for (const v of vals) entry.ids.push(v && v.$isblackholeDocument ? v._id : (v && v._id !== undefined && isObj(v) ? v._id : v));
|
|
201
|
+
entry.docs.push([d, local]);
|
|
202
|
+
}
|
|
203
|
+
for (const [target, entry] of byModel) {
|
|
204
|
+
const cond = { [foreignField]: { $in: entry.ids }, ...(opt.match || {}) };
|
|
205
|
+
let q = target.find(cond);
|
|
206
|
+
if (opt.select) q = q.select(opt.select);
|
|
207
|
+
if (opt.options) q = q.setOptions(opt.options);
|
|
208
|
+
if (opt.populate) q = q.populate(opt.populate);
|
|
209
|
+
q = q.lean(lean);
|
|
210
|
+
const found = await q.exec();
|
|
211
|
+
const index = new Map();
|
|
212
|
+
for (const f of found) {
|
|
213
|
+
const raw = f.$isblackholeDocument ? f._doc : f;
|
|
214
|
+
const ks = engine.values(raw, foreignField).flat();
|
|
215
|
+
for (const k of ks) { const key = String(k); let l = index.get(key); if (!l) index.set(key, l = []); l.push(f); }
|
|
216
|
+
}
|
|
217
|
+
for (const [d, local] of entry.docs) {
|
|
218
|
+
const key = (v) => String(v && v._id !== undefined && isObj(v) ? v._id : v);
|
|
219
|
+
let value;
|
|
220
|
+
if (virtual) {
|
|
221
|
+
const list = index.get(String(local)) || [];
|
|
222
|
+
value = virtual.options.count ? list.length : virtual.options.justOne ? list[0] || null : list;
|
|
223
|
+
} else if (Array.isArray(local)) {
|
|
224
|
+
value = local.map((v) => (index.get(key(v)) || [])[0]).filter((x) => x !== undefined);
|
|
225
|
+
if (opt.options && opt.options.limit) value = value.slice(0, opt.options.limit);
|
|
226
|
+
} else {
|
|
227
|
+
value = (index.get(key(local)) || [])[0];
|
|
228
|
+
if (value === undefined) value = null;
|
|
229
|
+
}
|
|
230
|
+
if (d.$isblackholeDocument) d.$__.populated.set(path, value); else engine.setPath(d, path, value);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ---------- Query ----------
|
|
236
|
+
const EVENT = { find: 'find', findOne: 'findOne', countDocuments: 'countDocuments', estimatedDocumentCount: 'estimatedDocumentCount', distinct: 'distinct', updateOne: 'updateOne', updateMany: 'updateMany', replaceOne: 'replaceOne', findOneAndUpdate: 'findOneAndUpdate', findOneAndReplace: 'findOneAndReplace', findOneAndDelete: 'findOneAndDelete', findOneAndRemove: 'findOneAndRemove', deleteOne: 'deleteOne', deleteMany: 'deleteMany' };
|
|
237
|
+
|
|
238
|
+
class Query {
|
|
239
|
+
constructor(model, op = null, conditions, options) {
|
|
240
|
+
this.model = model;
|
|
241
|
+
this.blackholeCollection = model.collection;
|
|
242
|
+
this.op = op;
|
|
243
|
+
this._conditions = {};
|
|
244
|
+
this._fields = undefined;
|
|
245
|
+
this._force = new Set();
|
|
246
|
+
this._update = undefined;
|
|
247
|
+
this._distinct = undefined;
|
|
248
|
+
this._path = undefined;
|
|
249
|
+
this._populate = [];
|
|
250
|
+
this._orFail = undefined;
|
|
251
|
+
this._transforms = [];
|
|
252
|
+
this.options = { ...(options || {}) };
|
|
253
|
+
if (conditions) this.merge(conditions);
|
|
254
|
+
this._executed = false;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// --- building ---
|
|
258
|
+
get schema() { return this.model.schema; }
|
|
259
|
+
getFilter() { return this._conditions; }
|
|
260
|
+
getQuery() { return this._conditions; }
|
|
261
|
+
getOptions() { return this.options; }
|
|
262
|
+
getUpdate() { return this._update; }
|
|
263
|
+
getPopulatedPaths() { return this._populate.map((p) => p.path); }
|
|
264
|
+
projection(v) { if (v === undefined) return engine.normalizeProjection(this._fields); this._fields = v; return this; }
|
|
265
|
+
merge(source) {
|
|
266
|
+
if (!source) return this;
|
|
267
|
+
if (source instanceof Query) { Object.assign(this._conditions, source._conditions); if (source._fields) this._fields = source._fields; Object.assign(this.options, source.options); return this; }
|
|
268
|
+
if (!isObj(source)) throw new ObjectParameterError(source, 'filter', 'find');
|
|
269
|
+
for (const k of Object.keys(source)) this._conditions[k] = source[k];
|
|
270
|
+
return this;
|
|
271
|
+
}
|
|
272
|
+
find(conditions, projection, options) { this.op = 'find'; this.merge(conditions); if (projection) this.select(projection); if (options) this.setOptions(options); return this; }
|
|
273
|
+
findOne(conditions, projection, options) { this.op = 'findOne'; this.merge(conditions); if (projection) this.select(projection); if (options) this.setOptions(options); return this; }
|
|
274
|
+
countDocuments(conditions) { this.op = 'countDocuments'; this.merge(conditions); return this; }
|
|
275
|
+
estimatedDocumentCount() { this.op = 'estimatedDocumentCount'; return this; }
|
|
276
|
+
distinct(field, conditions) { this.op = 'distinct'; this._distinct = field; this.merge(conditions); return this; }
|
|
277
|
+
updateOne(conditions, update, options) { return this._upd('updateOne', conditions, update, options); }
|
|
278
|
+
updateMany(conditions, update, options) { return this._upd('updateMany', conditions, update, options); }
|
|
279
|
+
replaceOne(conditions, replacement, options) { return this._upd('replaceOne', conditions, replacement, options); }
|
|
280
|
+
findOneAndUpdate(conditions, update, options) { return this._upd('findOneAndUpdate', conditions, update, options); }
|
|
281
|
+
findOneAndReplace(conditions, replacement, options) { return this._upd('findOneAndReplace', conditions, replacement, options); }
|
|
282
|
+
findOneAndDelete(conditions, options) { this.op = 'findOneAndDelete'; this.merge(conditions); if (options) this.setOptions(options); return this; }
|
|
283
|
+
findOneAndRemove(conditions, options) { this.op = 'findOneAndRemove'; this.merge(conditions); if (options) this.setOptions(options); return this; }
|
|
284
|
+
deleteOne(conditions, options) { this.op = 'deleteOne'; this.merge(conditions); if (options) this.setOptions(options); return this; }
|
|
285
|
+
deleteMany(conditions, options) { this.op = 'deleteMany'; this.merge(conditions); if (options) this.setOptions(options); return this; }
|
|
286
|
+
remove(conditions) { return this.deleteMany(conditions); }
|
|
287
|
+
update(conditions, update, options) { return this._upd('updateMany', conditions, update, { ...options, multi: true }); }
|
|
288
|
+
_upd(op, conditions, update, options) {
|
|
289
|
+
this.op = op;
|
|
290
|
+
if (update === undefined && isObj(conditions) && Object.keys(conditions).length && Object.keys(conditions).every((k) => k[0] === '$')) { update = conditions; conditions = undefined; }
|
|
291
|
+
this.merge(conditions);
|
|
292
|
+
if (update !== undefined) this._update = update;
|
|
293
|
+
if (options) this.setOptions(options);
|
|
294
|
+
return this;
|
|
295
|
+
}
|
|
296
|
+
set(path, val) { if (typeof path === 'object') { this._update = { ...(this._update || {}), $set: { ...((this._update || {}).$set || {}), ...path } }; } else { this._update = { ...(this._update || {}), $set: { ...((this._update || {}).$set || {}), [path]: val } }; } return this; }
|
|
297
|
+
setUpdate(u) { this._update = u; return this; }
|
|
298
|
+
setQuery(q) { this._conditions = q; return this; }
|
|
299
|
+
where(path, val) {
|
|
300
|
+
if (isObj(path)) return this.merge(path);
|
|
301
|
+
this._path = path;
|
|
302
|
+
if (arguments.length > 1) this._conditions[path] = val;
|
|
303
|
+
return this;
|
|
304
|
+
}
|
|
305
|
+
_cond(op, a, b) {
|
|
306
|
+
let path, val;
|
|
307
|
+
if (b === undefined && arguments.length < 3) { path = this._path; val = a; } else { path = a; val = b; }
|
|
308
|
+
if (path === undefined) throw new Error(`Must have a path before calling .${op.slice(1)}()`);
|
|
309
|
+
const cur = this._conditions[path];
|
|
310
|
+
this._conditions[path] = { ...(isOpObject(cur) ? cur : {}), [op]: val };
|
|
311
|
+
return this;
|
|
312
|
+
}
|
|
313
|
+
equals(v) { this._conditions[this._path] = v; return this; }
|
|
314
|
+
eq(v) { return this.equals(v); }
|
|
315
|
+
gt(a, b) { return this._cond('$gt', ...(arguments.length > 1 ? [a, b] : [a])); }
|
|
316
|
+
gte(a, b) { return this._cond('$gte', ...(arguments.length > 1 ? [a, b] : [a])); }
|
|
317
|
+
lt(a, b) { return this._cond('$lt', ...(arguments.length > 1 ? [a, b] : [a])); }
|
|
318
|
+
lte(a, b) { return this._cond('$lte', ...(arguments.length > 1 ? [a, b] : [a])); }
|
|
319
|
+
ne(a, b) { return this._cond('$ne', ...(arguments.length > 1 ? [a, b] : [a])); }
|
|
320
|
+
in(a, b) { return this._cond('$in', ...(arguments.length > 1 ? [a, b] : [a])); }
|
|
321
|
+
nin(a, b) { return this._cond('$nin', ...(arguments.length > 1 ? [a, b] : [a])); }
|
|
322
|
+
all(a, b) { return this._cond('$all', ...(arguments.length > 1 ? [a, b] : [a])); }
|
|
323
|
+
size(a, b) { return this._cond('$size', ...(arguments.length > 1 ? [a, b] : [a])); }
|
|
324
|
+
mod(a, b) { return this._cond('$mod', ...(arguments.length > 1 ? [a, b] : [a])); }
|
|
325
|
+
regex(a, b) { return this._cond('$regex', ...(arguments.length > 1 ? [a, b] : [a])); }
|
|
326
|
+
exists(a, b) { if (arguments.length === 0) return this._cond('$exists', true); if (typeof a === 'boolean' && arguments.length === 1) return this._cond('$exists', a); return this._cond('$exists', a, b === undefined ? true : b); }
|
|
327
|
+
elemMatch(path, cond) { if (typeof path === 'object' || typeof path === 'function') { cond = path; path = this._path; } this._conditions[path] = { ...(isOpObject(this._conditions[path]) ? this._conditions[path] : {}), $elemMatch: typeof cond === 'function' ? (() => { const q = new Query(this.model); cond(q); return q._conditions; })() : cond }; return this; }
|
|
328
|
+
and(arr) { this._conditions.$and = (this._conditions.$and || []).concat(arr); return this; }
|
|
329
|
+
or(arr) { this._conditions.$or = (this._conditions.$or || []).concat(arr); return this; }
|
|
330
|
+
nor(arr) { this._conditions.$nor = (this._conditions.$nor || []).concat(arr); return this; }
|
|
331
|
+
select(arg) {
|
|
332
|
+
if (arg === undefined || arg === null) return this;
|
|
333
|
+
const cur = (isObj(this._fields) ? this._fields : engine.normalizeProjection(this._fields)) || {};
|
|
334
|
+
const add = {};
|
|
335
|
+
if (typeof arg === 'string') {
|
|
336
|
+
for (const f of arg.split(/\s+/).filter(Boolean)) {
|
|
337
|
+
if (f[0] === '+') { this._force.add(f.slice(1)); if (Object.values(cur).some((v) => v)) add[f.slice(1)] = 1; }
|
|
338
|
+
else if (f[0] === '-') add[f.slice(1)] = 0;
|
|
339
|
+
else add[f] = 1;
|
|
340
|
+
}
|
|
341
|
+
} else if (Array.isArray(arg)) for (const f of arg) add[f] = 1;
|
|
342
|
+
else if (arg instanceof Map) for (const [k, v] of arg) add[k] = v;
|
|
343
|
+
else Object.assign(add, arg);
|
|
344
|
+
this._fields = { ...cur, ...add };
|
|
345
|
+
return this;
|
|
346
|
+
}
|
|
347
|
+
slice(path, val) { if (typeof path !== 'string') { val = path; path = this._path; } this._fields = { ...(this._fields || {}), [path]: { $slice: val } }; return this; }
|
|
348
|
+
sort(arg) {
|
|
349
|
+
if (arg === undefined || arg === null) return this;
|
|
350
|
+
const cur = engine.normalizeSort(this.options.sort);
|
|
351
|
+
const add = engine.normalizeSort(arg);
|
|
352
|
+
const map = new Map(cur);
|
|
353
|
+
for (const [k, d] of add) map.set(k, d);
|
|
354
|
+
this.options.sort = Object.fromEntries(map);
|
|
355
|
+
return this;
|
|
356
|
+
}
|
|
357
|
+
skip(n) { this.options.skip = n; return this; }
|
|
358
|
+
limit(n) { this.options.limit = n; return this; }
|
|
359
|
+
lean(v = true) { this.options.lean = v; return this; }
|
|
360
|
+
populate(...args) {
|
|
361
|
+
if (args.length === 2 && typeof args[0] === 'string' && (typeof args[1] === 'string' || isObj(args[1]) && !args[1].path)) { const [p, s] = args; this._populate.push(typeof s === 'string' ? { path: p, select: s } : { path: p, ...s }); return this; }
|
|
362
|
+
this._populate.push(...normalizePopulate(args));
|
|
363
|
+
return this;
|
|
364
|
+
}
|
|
365
|
+
setOptions(opts, overwrite) {
|
|
366
|
+
if (!opts) return this;
|
|
367
|
+
if (opts.populate) this.populate(opts.populate);
|
|
368
|
+
const { populate, projection, ...rest } = opts;
|
|
369
|
+
if (projection) this.select(projection);
|
|
370
|
+
if (overwrite) this.options = {};
|
|
371
|
+
Object.assign(this.options, rest);
|
|
372
|
+
return this;
|
|
373
|
+
}
|
|
374
|
+
orFail(err) { this._orFail = err === undefined ? true : err; return this; }
|
|
375
|
+
transform(fn) { this._transforms.push(fn); return this; }
|
|
376
|
+
session() { return this; } collation() { return this; } hint() { return this; } maxTimeMS() { return this; } allowDiskUse() { return this; } batchSize() { return this; } comment() { return this; } read() { return this; } readConcern() { return this; } maxScan() { return this; } j() { return this; } w() { return this; } wtimeout() { return this; } tailable() { return this; } snapshot() { return this; } cast() { return castFilter(this.schema, this._conditions); } writeConcern() { return this; } lean_() { return this; }
|
|
377
|
+
clone() { const q = new Query(this.model, this.op); q._conditions = clone(this._conditions); q._fields = this._fields && clone(this._fields); q._force = new Set(this._force); q._update = this._update && clone(this._update); q._distinct = this._distinct; q._populate = [...this._populate]; q.options = { ...this.options }; return q; }
|
|
378
|
+
explain() { const col = this.model.$collection; col.load(); const filter = castFilter(this.schema, this._conditions); const ids = col.plan(filter); return Promise.resolve({ queryPlanner: { namespace: col.name, winningPlan: { stage: ids ? 'IXSCAN' : 'COLLSCAN', candidates: ids ? ids.length : col.docs.size } } }); }
|
|
379
|
+
|
|
380
|
+
// --- execution ---
|
|
381
|
+
then(res, rej) { return this.exec().then(res, rej); }
|
|
382
|
+
catch(rej) { return this.exec().catch(rej); }
|
|
383
|
+
finally(fn) { return this.exec().finally(fn); }
|
|
384
|
+
get [Symbol.toStringTag]() { return 'Query'; }
|
|
385
|
+
|
|
386
|
+
async exec(callback) {
|
|
387
|
+
if (!this.op) throw new Error('Query was not given an operation. Call find(), findOne(), updateOne() or similar first.');
|
|
388
|
+
const schema = this.model.schema;
|
|
389
|
+
const event = EVENT[this.op] || this.op;
|
|
390
|
+
let result;
|
|
391
|
+
try {
|
|
392
|
+
await runHooks(schema, 'pre', event, this);
|
|
393
|
+
result = this._run();
|
|
394
|
+
if (this._populate.length && result) await populateResults(this.model, result, this._populate, !!this.options.lean);
|
|
395
|
+
for (const t of this._transforms) result = t(result, this);
|
|
396
|
+
if (this._orFail) {
|
|
397
|
+
const empty = result === null || result === undefined || (Array.isArray(result) && result.length === 0) || (result && result.deletedCount === 0) || (result && result.matchedCount === 0 && 'matchedCount' in result);
|
|
398
|
+
if (empty) { const err = typeof this._orFail === 'function' ? this._orFail.call(this) : this._orFail === true ? new DocumentNotFoundError(this._conditions, this.model.modelName) : this._orFail; throw err; }
|
|
399
|
+
}
|
|
400
|
+
await runHooks(schema, 'post', event, this, [result]);
|
|
401
|
+
} catch (e) {
|
|
402
|
+
const err = await runErrorHooks(schema, event, this, e);
|
|
403
|
+
if (callback) return callback(err);
|
|
404
|
+
throw err;
|
|
405
|
+
}
|
|
406
|
+
if (callback) return callback(null, result);
|
|
407
|
+
return result;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
_projection() { return effectiveProjection(this.schema, this._fields, this._force); }
|
|
411
|
+
|
|
412
|
+
// turns stored (shared) documents into results: project, copy, wrap
|
|
413
|
+
_out(stored, proj) {
|
|
414
|
+
const lean = this.options.lean;
|
|
415
|
+
let d = proj ? engine.project(stored, proj) : stored;
|
|
416
|
+
d = clone(d);
|
|
417
|
+
if (lean) return d;
|
|
418
|
+
return this.model.$hydrate(d, proj);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
_run() {
|
|
422
|
+
const model = this.model;
|
|
423
|
+
const col = model.$collection;
|
|
424
|
+
col.load();
|
|
425
|
+
const schema = model.schema;
|
|
426
|
+
const filter = castFilter(schema, this._conditions);
|
|
427
|
+
const o = this.options;
|
|
428
|
+
switch (this.op) {
|
|
429
|
+
case 'find': {
|
|
430
|
+
const proj = this._projection();
|
|
431
|
+
const found = col.find(filter, { sort: o.sort, skip: o.skip || 0, limit: o.limit || 0 });
|
|
432
|
+
const out = new Array(found.length);
|
|
433
|
+
for (let i = 0; i < found.length; i++) out[i] = this._out(found[i], proj);
|
|
434
|
+
return out;
|
|
435
|
+
}
|
|
436
|
+
case 'findOne': {
|
|
437
|
+
const found = col.find(filter, { sort: o.sort, skip: o.skip || 0, limit: 1 })[0];
|
|
438
|
+
return found ? this._out(found, this._projection()) : null;
|
|
439
|
+
}
|
|
440
|
+
case 'countDocuments': return col.count(filter);
|
|
441
|
+
case 'estimatedDocumentCount': return col.docs.size;
|
|
442
|
+
case 'distinct': {
|
|
443
|
+
const seen = new Map();
|
|
444
|
+
for (const d of col.scan(filter)) for (const v of engine.values(d, this._distinct)) for (const x of (Array.isArray(v) ? v : [v])) { const k = typeof x === 'object' && x !== null && !(x instanceof Date) && !(x instanceof ObjectId) ? JSON.stringify(x) : `${typeof x}:${x instanceof Date ? x.getTime() : String(x)}`; if (!seen.has(k)) seen.set(k, x); }
|
|
445
|
+
return [...seen.values()].map(clone);
|
|
446
|
+
}
|
|
447
|
+
case 'deleteOne': { const t = col.findOne(filter, o.sort); if (t) col.remove(t._id); return { acknowledged: true, deletedCount: t ? 1 : 0 }; }
|
|
448
|
+
case 'deleteMany': { const targets = [...col.scan(filter)]; for (const t of targets) col.remove(t._id); return { acknowledged: true, deletedCount: targets.length }; }
|
|
449
|
+
case 'findOneAndDelete': case 'findOneAndRemove': {
|
|
450
|
+
const t = col.findOne(filter, o.sort);
|
|
451
|
+
if (!t) return this._meta(null, false);
|
|
452
|
+
const out = this._out(t, this._projection());
|
|
453
|
+
col.remove(t._id);
|
|
454
|
+
return this._meta(out, true);
|
|
455
|
+
}
|
|
456
|
+
case 'updateOne': case 'updateMany': case 'replaceOne': case 'findOneAndUpdate': case 'findOneAndReplace': return this._runUpdate(col, filter);
|
|
457
|
+
default: throw new Error(`Unsupported query operation: ${this.op}`);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
_meta(value, updatedExisting, upserted) {
|
|
462
|
+
const o = this.options;
|
|
463
|
+
if (o.rawResult || o.includeResultMetadata) return { value, lastErrorObject: { n: value ? 1 : 0, updatedExisting, ...(upserted ? { upserted } : {}) }, ok: 1 };
|
|
464
|
+
return value;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
_runUpdate(col, filter) {
|
|
468
|
+
const model = this.model;
|
|
469
|
+
const schema = model.schema;
|
|
470
|
+
const o = this.options;
|
|
471
|
+
const replace = this.op === 'replaceOne' || this.op === 'findOneAndReplace' || o.overwrite;
|
|
472
|
+
const single = this.op === 'updateOne' || this.op === 'replaceOne' || this.op === 'findOneAndUpdate' || this.op === 'findOneAndReplace' || (this.op === 'updateMany' && false);
|
|
473
|
+
const findAnd = this.op.startsWith('findOneAnd');
|
|
474
|
+
const returnNew = o.new === true || o.returnDocument === 'after';
|
|
475
|
+
let upd = this._update;
|
|
476
|
+
if (upd === undefined) upd = {};
|
|
477
|
+
if (Array.isArray(upd)) throw new Error('Pipeline-style updates are not supported by blackhole.db');
|
|
478
|
+
let cast;
|
|
479
|
+
let replacement;
|
|
480
|
+
if (replace || (!Object.keys(upd).some((k) => k[0] === '$') && o.overwrite)) {
|
|
481
|
+
replacement = S.castDocument(schema, upd.$isblackholeDocument ? upd.toObject() : upd, '', { strict: o.strict });
|
|
482
|
+
} else cast = castUpdate(schema, upd, o);
|
|
483
|
+
if (o.runValidators && cast) {
|
|
484
|
+
const errors = {};
|
|
485
|
+
const pending = [];
|
|
486
|
+
for (const op of ['$set', '$setOnInsert']) for (const [p, v] of Object.entries(cast[op] || {})) { const node = nodeFor(schema, p); if (node) S.validateNode(node, p, v, this, errors, pending); }
|
|
487
|
+
if (Object.keys(errors).length) { const err = new ValidationError({ $__name: model.modelName }); for (const [p, e] of Object.entries(errors)) err.addError(p, e); throw err; }
|
|
488
|
+
}
|
|
489
|
+
const SAFE = new Set(['$set', '$setOnInsert', '$unset', '$inc', '$mul', '$min', '$max', '$currentDate']);
|
|
490
|
+
const shallowSafe = !!cast && Object.keys(cast).every((op) => SAFE.has(op) && Object.keys(cast[op]).every((p) => !p.includes('.')));
|
|
491
|
+
const targets = single ? [col.findOne(filter, o.sort)].filter(Boolean) : [...col.scan(filter)];
|
|
492
|
+
const proj = findAnd ? this._projection() : null;
|
|
493
|
+
let modified = 0;
|
|
494
|
+
let before = null, after = null;
|
|
495
|
+
for (const stored of targets) {
|
|
496
|
+
// Updates that only touch top-level fields never mutate nested values in place, so a
|
|
497
|
+
// shallow copy is enough. This keeps large documents (chapter lists) from being deep-copied.
|
|
498
|
+
const work = shallowSafe ? { ...stored } : clone(stored);
|
|
499
|
+
let changed;
|
|
500
|
+
if (replacement) {
|
|
501
|
+
const next = { ...clone(replacement), _id: stored._id };
|
|
502
|
+
S.applyDefaults(schema, next, next);
|
|
503
|
+
if (schema.options.versionKey && stored[schema.options.versionKey] !== undefined) next[schema.options.versionKey] = stored[schema.options.versionKey];
|
|
504
|
+
const ts = schema.options.timestamps;
|
|
505
|
+
if (ts && ts.createdAt && stored[ts.createdAt] !== undefined) next[ts.createdAt] = stored[ts.createdAt];
|
|
506
|
+
if (ts && ts.updatedAt && o.timestamps !== false) next[ts.updatedAt] = new Date();
|
|
507
|
+
col.replace(next, stored);
|
|
508
|
+
changed = true; after = next; before = stored;
|
|
509
|
+
} else {
|
|
510
|
+
changed = engine.applyUpdate(work, cast, { arrayFilters: o.arrayFilters, filter, inserting: false });
|
|
511
|
+
if (changed) { col.replace(work, stored); }
|
|
512
|
+
after = changed ? work : stored; before = stored;
|
|
513
|
+
}
|
|
514
|
+
if (changed) modified++;
|
|
515
|
+
}
|
|
516
|
+
if (targets.length === 0 && o.upsert) {
|
|
517
|
+
const doc = engine.seedFromFilter(filter);
|
|
518
|
+
if (replacement) Object.assign(doc, clone(replacement)); else engine.applyUpdate(doc, cast, { inserting: true, arrayFilters: o.arrayFilters });
|
|
519
|
+
if (o.setDefaultsOnInsert !== false) S.applyDefaults(schema, doc, doc);
|
|
520
|
+
if (schema.paths._id && doc._id === undefined) doc._id = new ObjectId();
|
|
521
|
+
const ts = schema.options.timestamps;
|
|
522
|
+
if (ts && replacement) { const now = new Date(); if (ts.createdAt) doc[ts.createdAt] = now; if (ts.updatedAt) doc[ts.updatedAt] = now; }
|
|
523
|
+
if (schema.options.versionKey && doc[schema.options.versionKey] === undefined) doc[schema.options.versionKey] = 0;
|
|
524
|
+
col.insert(doc);
|
|
525
|
+
if (findAnd) return this._meta(returnNew ? this._out(doc, proj) : null, false, doc._id);
|
|
526
|
+
return { acknowledged: true, matchedCount: 0, modifiedCount: 0, upsertedCount: 1, upsertedId: doc._id };
|
|
527
|
+
}
|
|
528
|
+
if (findAnd) {
|
|
529
|
+
if (!targets.length) return this._meta(null, false);
|
|
530
|
+
return this._meta(this._out(returnNew ? after : before, proj), true);
|
|
531
|
+
}
|
|
532
|
+
return { acknowledged: true, matchedCount: targets.length, modifiedCount: modified, upsertedCount: 0, upsertedId: null };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// --- cursors / iteration ---
|
|
536
|
+
async *[Symbol.asyncIterator]() {
|
|
537
|
+
const docs = await this.clone().exec();
|
|
538
|
+
for (const d of docs) yield d;
|
|
539
|
+
}
|
|
540
|
+
cursor() {
|
|
541
|
+
const q = this;
|
|
542
|
+
const it = (async function* () { yield* q[Symbol.asyncIterator](); })();
|
|
543
|
+
it.next = it.next.bind(it);
|
|
544
|
+
it.close = async () => {};
|
|
545
|
+
it.eachAsync = async (fn) => { for await (const d of it) await fn(d); };
|
|
546
|
+
it.toArray = async () => { const out = []; for await (const d of it) out.push(d); return out; };
|
|
547
|
+
return it;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
module.exports = { Query, castFilter, castUpdate, populateResults, normalizePopulate, nodeFor, EVENT };
|