@ewb/mongoose-query 1.0.3 → 1.0.5

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/README.md CHANGED
@@ -13,7 +13,7 @@ function queryMiddleware(req, next) {
13
13
  }
14
14
 
15
15
  // This is used to set some logic for query to that model. Model for query is set in the controllers.
16
- const modelQuery = new QueryModel<Doc>({
16
+ const modelQueryOptions = new QueryOptions<Doc>({
17
17
  limit: 10,
18
18
  query: ['name', 'slug'], // Valid queries for model. Filters all other fields
19
19
  select: ['_id', 'name', 'slug'], // Valid select fields for search,
@@ -24,6 +24,9 @@ const modelQuery = new QueryModel<Doc>({
24
24
  }]
25
25
  });
26
26
 
27
+ const User = mongoose.model('user', UserSchema);
28
+ const modelQuery = new ModelQuery(User, modelQueryOptions);
29
+
27
30
  function someController(req, res) {
28
31
  // add organization ID to root query so query will always search inside organization
29
32
  req.mongooseQuery.addToRoot({ organization: req.organization._id });
package/lib/Query.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import mongoose from 'mongoose';
2
- import { IQueryPopulate } from './QueryModel.js';
2
+ import { IQueryPopulate } from './QueryOptions.js';
3
3
  import { IMongooseQueryOptions } from './utils/Query.utils.js';
4
4
  import { IQueryOptions, MongooseSortSelectValue, QueryType } from './utils/types.js';
5
5
  export declare class Query<R extends object, T extends object = object, Q extends IMongooseQueryOptions = IMongooseQueryOptions> {
@@ -1,65 +1,47 @@
1
1
  import mongoose from 'mongoose';
2
2
  import { Query } from './Query.js';
3
- export interface ModelSearchPopulate<T extends any, K extends keyof T> {
4
- path: K;
5
- select: (T[K] extends object ? keyof T[K] : string)[];
6
- ref?: string;
7
- lookupRef?: string;
8
- onFindOne?: boolean;
9
- onPatch?: boolean;
10
- onPost?: boolean;
11
- onAll?: boolean;
12
- onSearch?: boolean;
13
- populate?: mongoose.PopulateOptions[];
3
+ import { IQueryOptionsPopulate, QueryOptions } from './QueryOptions.js';
4
+ export interface QueryFindOpts {
5
+ populate?: boolean;
6
+ select?: boolean;
14
7
  }
15
- interface ModelSearchOptsSub<T extends object, K extends keyof T> {
16
- sub: K;
17
- populate: ModelSearchPopulate<T[K], keyof T[K]>[];
18
- }
19
- interface ModelSearchOpts<T extends object> {
20
- editFields?: (keyof T)[];
21
- privateFields?: (keyof T)[];
22
- query?: (keyof T)[];
23
- select?: (keyof T)[];
24
- defaultSelect?: (keyof T)[] | string[];
25
- sort?: (keyof T)[];
26
- populate?: ModelSearchPopulate<T, keyof T>[];
27
- limit?: number;
28
- subs?: ModelSearchOptsSub<T, keyof T>[];
29
- updateDateKey?: keyof T;
30
- }
31
- export interface IQueryPopulate {
32
- path: string;
33
- select?: string[];
34
- }
35
- type IModelQuery = mongoose.QueryWithHelpers<unknown, unknown>;
36
- export declare const toValidSelectRegexp: (select: string | number | symbol) => RegExp;
37
- export declare const toValidSortRegexp: (sort: string | number | symbol) => RegExp;
38
- export declare const toValidTextRegexp: (str: string) => RegExp | "";
8
+ type SubDocArray<T extends object, K extends keyof T> = T[K][];
9
+ type SubDocItem<T extends object, K extends keyof T> = (T[K] extends [] ? T[K][0] : null) | null;
39
10
  export declare class QueryModel<T extends object> {
40
- private opts;
41
- constructor(opts?: ModelSearchOpts<T>);
42
- get publicFields(): (keyof T)[];
43
- get privateFields(): (keyof T)[];
44
- get populate(): ModelSearchPopulate<T, keyof T>[];
45
- get subs(): ModelSearchOptsSub<T, keyof T>[];
46
- get updateDateKey(): keyof T;
47
- get query(): (keyof T)[];
48
- createSearchQuery(query: Query<any, T>): mongoose.FilterQuery<T>;
49
- setPopulate(modelQuery: IModelQuery, query: Query<T>): void;
50
- getValidPopulate(queryPopulate: IQueryPopulate[], sub?: keyof T): ModelSearchPopulate<any, any>[];
51
- setLimitAndSkip(modelQuery: IModelQuery, query: Query<T>): void;
52
- setSelect(modelQuery: IModelQuery, query: Query<T>, overrideValid?: (keyof T)[]): void;
53
- setSort(modelQuery: IModelQuery, query: Query<T>): void;
54
- setProjection(modelQuery: IModelQuery, query: Query<T>): void;
55
- getSubPopulateLookup<K extends keyof T>(query: Query<T>, sub: K): any[];
56
- getSubFilterConditionAndMatch(subQuery: mongoose.FilterQuery<T>, sub: keyof T): {
57
- $filter: {
58
- input: string;
59
- as: string;
60
- cond: any;
61
- };
62
- $match: any;
63
- };
11
+ private _model;
12
+ private options;
13
+ constructor(_model: mongoose.Model<T>, options: QueryOptions<T>);
14
+ get model(): mongoose.Model<T, {}, {}, {}, mongoose.IfAny<T, any, mongoose.Document<unknown, {}, T> & Omit<mongoose.Require_id<T>, never>>, any>;
15
+ create<B extends Partial<T>>(body: B): Promise<mongoose.IfAny<T, any, mongoose.Document<unknown, {}, T> & Omit<mongoose.Require_id<T>, never>>>;
16
+ json<D extends mongoose.Document>(doc: D): Promise<any>;
17
+ search(query: Query<T>): Promise<{
18
+ data: T[];
19
+ count: number;
20
+ limit: number;
21
+ skip: number;
22
+ }>;
23
+ findOne(query: Query<T>, opts?: QueryFindOpts): Promise<mongoose.IfAny<T, any, mongoose.Document<unknown, {}, T> & Omit<mongoose.Require_id<T>, never>>>;
24
+ findOneAndUpdate(query: Query<T>, filter: mongoose.FilterQuery<T>, update: mongoose.UpdateQuery<T>): Promise<mongoose.IfAny<T, any, mongoose.Document<unknown, {}, T> & Omit<mongoose.Require_id<T>, never>>>;
25
+ deleteOne(filter: mongoose.FilterQuery<T>): Promise<mongoose.mongo.DeleteResult>;
26
+ populate(query: Query<T>, doc: T | T[any], type?: keyof IQueryOptionsPopulate<T, any>): Promise<void>;
27
+ getPopulates(type: keyof IQueryOptionsPopulate<T, any>): IQueryOptionsPopulate<T, keyof T>[];
28
+ updateMany(query: mongoose.FilterQuery<T>, $in: mongoose.Types.ObjectId[], body: Partial<T>): Promise<mongoose.UpdateWriteOpResult>;
29
+ deleteMany(query: mongoose.FilterQuery<T>, $in: mongoose.Types.ObjectId[]): Promise<mongoose.mongo.DeleteResult>;
30
+ subCreate<K extends keyof T>(sub: K, query: Query<T>, body: any): Promise<(T[K] extends [] ? T[K][0] : null) | null>;
31
+ subSearch<K extends keyof T>(sub: K, query: Query<T>, rootQuery: mongoose.FilterQuery<T>): Promise<{
32
+ count: number;
33
+ limit: number;
34
+ skip: number;
35
+ data: SubDocArray<T, K>;
36
+ }>;
37
+ subFindOne<K extends keyof T>(sub: K, query: Query<T>, subQuery: mongoose.FilterQuery<T[K]>): Promise<SubDocItem<T, K>>;
38
+ subFindOneAndUpdate<K extends keyof T>(sub: K, query: Query<T>, subQuery: mongoose.FilterQuery<T[K]>, body: T[K]): Promise<(T[K] extends [] ? T[K][0] : null) | null>;
39
+ subDelete<K extends keyof T>(sub: K, query: Query<T>, subQuery: mongoose.FilterQuery<T[K]>): Promise<(T[K] extends [] ? T[K][0] : null) | null>;
40
+ subPopulate<R extends Request, SD, K extends keyof T>(query: Query<T>, subDoc: SD, sub: K, type?: keyof IQueryOptionsPopulate<T, K>): Promise<void[]>;
41
+ getSubPopulate<K extends keyof T>(sub: K, type: keyof IQueryOptionsPopulate<T, K>): IQueryOptionsPopulate<T[keyof T], keyof T[keyof T]>[];
42
+ private getSubDocument;
43
+ validateBody(body: Partial<T>): any[];
44
+ toJSON(_: unknown, ret: T): void;
45
+ private populateDoc;
64
46
  }
65
47
  export {};
package/lib/QueryModel.js CHANGED
@@ -1,214 +1,250 @@
1
1
  import mongoose from 'mongoose';
2
- import { DEFAULT_LIMIT } from './utils/constants.js';
3
- export const toValidSelectRegexp = (select) => new RegExp(`^${String(select)}(\..|$)`);
4
- export const toValidSortRegexp = (sort) => new RegExp(`^(\\+|-)?(${String(sort)}|text)$`);
5
- export const toValidTextRegexp = (str) => typeof str === 'string'
6
- ? new RegExp(str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i')
7
- : '';
2
+ import { toValidTextRegexp, } from './QueryOptions.js';
8
3
  export class QueryModel {
9
- constructor(opts = {}) {
10
- this.opts = opts;
11
- }
12
- get publicFields() {
13
- return this.opts.editFields;
14
- }
15
- get privateFields() {
16
- return this.opts.privateFields;
17
- }
18
- get populate() {
19
- return this.opts.populate;
20
- }
21
- get subs() {
22
- return this.opts.subs;
23
- }
24
- get updateDateKey() {
25
- return this.opts.updateDateKey;
26
- }
27
- get query() {
28
- return this.opts.query;
4
+ constructor(_model, options) {
5
+ this._model = _model;
6
+ this.options = options;
7
+ this.toJSON = this.toJSON.bind(this);
8
+ }
9
+ get model() {
10
+ return this._model;
11
+ }
12
+ async create(body) {
13
+ const newDoc = new this._model(body);
14
+ await newDoc.validate();
15
+ await newDoc.save();
16
+ return newDoc;
17
+ }
18
+ async json(doc) {
19
+ return doc.toJSON({ transform: this.toJSON });
20
+ }
21
+ async search(query) {
22
+ const findQuery = this.options.createSearchQuery(query);
23
+ const modelFind = this._model.find(findQuery, query.options);
24
+ this.options.setPopulate(modelFind, query);
25
+ this.options.setLimitAndSkip(modelFind, query);
26
+ this.options.setSort(modelFind, query);
27
+ this.options.setSelect(modelFind, query, query.select);
28
+ const { skip = query.skip, limit = query.limit } = modelFind.getOptions();
29
+ const [data, count] = await Promise.all([
30
+ modelFind.lean().exec(),
31
+ this._model.find(findQuery).count(),
32
+ ]);
33
+ return { data: data, count, limit, skip };
34
+ }
35
+ async findOne(query, opts = {}) {
36
+ const filter = query.root || query.createQuery();
37
+ const modelFindOne = this._model.findOne(filter);
38
+ if (opts.populate)
39
+ this.options.setPopulate(modelFindOne, query);
40
+ this.options.setSelect(modelFindOne, query, opts.select ? undefined : []);
41
+ this.options.setProjection(modelFindOne, query);
42
+ return modelFindOne.exec();
43
+ }
44
+ async findOneAndUpdate(query, filter, update) {
45
+ if (this.options.updateDateKey) {
46
+ if ('$set' in update) {
47
+ update['$set'][this.options.updateDateKey] = new Date();
48
+ }
49
+ else {
50
+ update[this.options.updateDateKey] = new Date();
51
+ }
52
+ }
53
+ const modelUpdateOne = this._model.findOneAndUpdate(filter, update, {
54
+ new: true,
55
+ });
56
+ this.options.setPopulate(modelUpdateOne, query);
57
+ this.options.setSelect(modelUpdateOne, query);
58
+ return modelUpdateOne.exec();
29
59
  }
30
- createSearchQuery(query) {
31
- return query.createQuery({ noRoot: false, query: this.opts.query });
60
+ async deleteOne(filter) {
61
+ return this._model.deleteOne(filter);
32
62
  }
33
- setPopulate(modelQuery, query) {
34
- let populate = [];
35
- if (query.populate.length > 0 && this.opts.populate) {
36
- populate = this.getValidPopulate(query.populate).map((x) => ({
37
- ...x,
38
- select: x.select.join(' '),
39
- }));
40
- }
41
- if (query.rootPopulate.length > 0) {
42
- populate.push(...query.rootPopulate);
63
+ async populate(query, doc, type) {
64
+ try {
65
+ const populates = type ? this.getPopulates(type) : [];
66
+ populates.push(...this.options.getValidPopulate(query.populate));
67
+ await this.populateDoc(doc, populates);
43
68
  }
44
- if (populate.length > 0) {
45
- modelQuery.populate(populate);
69
+ catch (e) {
46
70
  }
47
71
  }
48
- getValidPopulate(queryPopulate, sub) {
49
- let checkPop = this.opts.populate;
50
- if (this.opts.subs && sub) {
51
- const found = this.opts.subs.find((x) => x.sub === sub);
52
- if (!found || !found.populate || found.populate.length === 0)
53
- return [];
54
- checkPop = found.populate;
55
- }
56
- if (!checkPop)
72
+ getPopulates(type) {
73
+ const populate = this.options.populate;
74
+ if (!populate || populate.length === 0) {
57
75
  return [];
58
- return queryPopulate
59
- .map((pop) => {
60
- const found = checkPop.find((x) => x.path === pop.path);
61
- if (!found)
62
- return null;
63
- const select = pop.select?.filter((x) => found.select.includes(x)) || [];
64
- return {
65
- path: pop.path,
66
- select: select.length > 0 ? select : found.select,
67
- ...(found.populate ? { populate: found.populate } : {}),
68
- };
69
- })
70
- .filter(Boolean);
71
- }
72
- setLimitAndSkip(modelQuery, query) {
73
- if (query.export)
74
- return;
75
- modelQuery.skip(query.skip ?? 0);
76
- modelQuery.limit(query.limit ?? this.opts.limit ?? DEFAULT_LIMIT);
77
- }
78
- setSelect(modelQuery, query, overrideValid) {
79
- const valids = overrideValid || this.opts.select;
80
- let selects = valids || [];
81
- if (valids && valids.length > 0 && query.select.length > 0) {
82
- selects = query.select.filter((select) => valids.some((valid) => String(select).match(toValidSelectRegexp(valid))));
83
- }
84
- else if (this.opts.defaultSelect) {
85
- selects = this.opts.defaultSelect;
86
- }
87
- if (selects.length > 0) {
88
- modelQuery.select(selects.join(' '));
89
76
  }
77
+ return populate.filter((x) => x[type] || x.onAll);
90
78
  }
91
- setSort(modelQuery, query) {
92
- if (query.sort.length > 0) {
93
- if (this.opts.sort) {
94
- const validSorts = query.sort.filter((x) => this.opts.sort.some((y) => String(x).match(toValidSortRegexp(y))));
95
- modelQuery.sort(sortArrayToSortObject(validSorts, query.hasTextSearch));
96
- }
97
- else {
98
- modelQuery.sort(sortArrayToSortObject(query.sort, query.hasTextSearch));
99
- }
100
- }
79
+ async updateMany(query, $in, body) {
80
+ return this._model.updateMany({ ...query, _id: { $in } }, { $set: body });
81
+ }
82
+ async deleteMany(query, $in) {
83
+ return this._model.deleteMany({ ...query, _id: { $in } });
101
84
  }
102
- setProjection(modelQuery, query) {
103
- if (query.projection) {
104
- modelQuery.projection(query.projection);
105
- query.projection = undefined;
85
+ async subCreate(sub, query, body) {
86
+ if (!('_id' in body)) {
87
+ body['_id'] = new mongoose.Types.ObjectId();
106
88
  }
89
+ await this._model.updateOne({ ...query.root }, { $push: { [sub]: body } });
90
+ return this.subFindOne(sub, query, { _id: body._id });
107
91
  }
108
- getSubPopulateLookup(query, sub) {
109
- if (!this.opts.subs)
110
- return [];
111
- const validPopulate = this.opts.subs.find((x) => x.sub === sub);
112
- if (!validPopulate)
113
- return [];
92
+ async subSearch(sub, query, rootQuery) {
93
+ const subQuery = query.createQuery({ noRoot: true });
114
94
  const populate = query.populate;
115
- const $lookups = [];
116
- if (populate.length > 0) {
117
- for (const pop of populate) {
118
- const found = validPopulate.populate.find((x) => x.path === pop.path);
119
- if (!found)
120
- continue;
121
- const select = pop.select
122
- ? found.select.filter((x) => pop.select.includes(String(x)))
123
- : found.select;
124
- $lookups.push(...[
125
- {
126
- $lookup: {
127
- from: found.lookupRef || `${pop.path}s`,
128
- localField: `${String(sub)}.${pop.path}`,
129
- foreignField: '_id',
130
- as: pop.path,
131
- },
132
- },
133
- ...(pop.select
134
- ? [
135
- {
136
- $project: {
137
- _id: 1,
138
- [sub]: 1,
139
- count: 1,
140
- [pop.path]: select.reduce((obj, item) => ({ ...obj, [item]: 1 }), {}),
141
- },
142
- },
143
- ]
144
- : []),
145
- ]);
95
+ const limit = query.limit;
96
+ const skip = query.skip;
97
+ const $lookups = this.options.getSubPopulateLookup(query, sub);
98
+ const { $filter, $match } = this.options.getSubFilterConditionAndMatch(subQuery, sub);
99
+ const pipeline = [
100
+ { $match: rootQuery },
101
+ {
102
+ $project: {
103
+ [sub]: { $filter },
104
+ count: { $size: `$${String(sub)}` },
105
+ },
106
+ },
107
+ { $unwind: `$${String(sub)}` },
108
+ ...(skip ? [{ $skip: skip }] : []),
109
+ ...(limit ? [{ $limit: limit }] : []),
110
+ ...$lookups,
111
+ ];
112
+ if (Object.keys($match).length > 0) {
113
+ for (const key in $match) {
114
+ if ($match.hasOwnProperty(key)) {
115
+ const [path, pathKey] = key.split('.');
116
+ if (pathKey && populate.some((pop) => pop.path === path)) {
117
+ $match[`${path}.${pathKey}`] = toValidTextRegexp($match[key]);
118
+ }
119
+ else if (typeof $match[key] === 'string') {
120
+ $match[`${String(sub)}.${path}`] = toValidTextRegexp($match[key]);
121
+ }
122
+ else {
123
+ $match[`${String(sub)}.${path}`] = $match[key];
124
+ }
125
+ delete $match[key];
126
+ }
146
127
  }
147
- }
148
- return $lookups;
149
- }
150
- getSubFilterConditionAndMatch(subQuery, sub) {
151
- const cond = {};
152
- let $match = {};
153
- for (const key in subQuery) {
154
- const v = subQuery[key];
155
- if (key !== '$and' && !Array.isArray(v)) {
156
- const $and = [];
157
- const [newItem, toMatch] = queryToSubFilter(key, subQuery[key]);
158
- if (newItem.length > 0) {
159
- $and.push(...newItem);
128
+ pipeline.push({ $match });
129
+ }
130
+ const arr = await this._model.aggregate(pipeline);
131
+ return arr.reduce((obj, item) => {
132
+ const data = { ...item[sub] };
133
+ for (const key in item) {
134
+ if (!['_id', 'count', 'skip', 'limit', sub].includes(key)) {
135
+ data[key] = Array.isArray(item[key]) ? item[key][0] : item[key];
136
+ }
137
+ }
138
+ return {
139
+ count: item.count,
140
+ data: [...obj.data, data],
141
+ skip: obj.skip,
142
+ limit: obj.limit,
143
+ };
144
+ }, { count: 0, data: [], skip, limit });
145
+ }
146
+ async subFindOne(sub, query, subQuery) {
147
+ const subDoc = await this._model.findOne({
148
+ ...query.root,
149
+ [sub]: { $elemMatch: subQuery },
150
+ }, { [`${String(sub)}.$`]: 1 });
151
+ return this.getSubDocument(sub, subDoc);
152
+ }
153
+ async subFindOneAndUpdate(sub, query, subQuery, body) {
154
+ const $set = {};
155
+ for (const key in body) {
156
+ $set[`${String(sub)}.$.${key}`] = body[key];
157
+ }
158
+ await this._model.updateOne({
159
+ ...query.root,
160
+ [sub]: { $elemMatch: subQuery },
161
+ }, { $set });
162
+ return this.subFindOne(sub, query, subQuery);
163
+ }
164
+ async subDelete(sub, query, subQuery) {
165
+ const subDoc = await this.subFindOne(sub, query, subQuery);
166
+ if (!subDoc)
167
+ return null;
168
+ await this._model.updateOne({
169
+ ...query.root,
170
+ [sub]: { $elemMatch: subQuery },
171
+ }, { $pull: { [sub]: { _id: subDoc._id } } });
172
+ return subDoc;
173
+ }
174
+ async subPopulate(query, subDoc, sub, type) {
175
+ const populates = type ? this.getSubPopulate(sub, type) : [];
176
+ populates.push(...this.options.getValidPopulate(query.populate, sub));
177
+ return this.populateDoc(subDoc, populates, sub);
178
+ }
179
+ getSubPopulate(sub, type) {
180
+ const subs = this.options.subs;
181
+ if (!subs)
182
+ return [];
183
+ const docSub = subs.find((x) => x.sub === sub);
184
+ if (!docSub)
185
+ return [];
186
+ return docSub.populate.filter((x) => x[type] || x.onAll);
187
+ }
188
+ getSubDocument(key, doc) {
189
+ if (!doc)
190
+ return null;
191
+ const array = doc[key];
192
+ if (array && Array.isArray(array)) {
193
+ return array[0] || null;
194
+ }
195
+ return null;
196
+ }
197
+ validateBody(body) {
198
+ const invalidFields = [];
199
+ if (this.options.publicFields) {
200
+ for (const key in body) {
201
+ if (body.hasOwnProperty(key)) {
202
+ if (!this.options.publicFields.includes(key)) {
203
+ invalidFields.push(key);
204
+ }
160
205
  }
161
- $match = { ...$match, ...toMatch };
162
- cond['$and'] = $and;
163
206
  }
164
207
  }
165
- const $filter = { input: `$${String(sub)}`, as: 'subdoc', cond };
166
- return { $filter, $match };
208
+ return invalidFields.length > 0 ? invalidFields : null;
167
209
  }
168
- }
169
- function queryToSubFilter(key, value) {
170
- if (!value)
171
- return [[], {}];
172
- if (typeof value === 'object') {
173
- if ('$in' in value && value.$in) {
174
- return [
175
- [{ $in: [`$$subdoc.${String(key)}`, value.$in.map(toCorrectIdValue)] }],
176
- {},
177
- ];
178
- }
179
- if ('$nin' in value && value.$nin) {
180
- return [
181
- value.$nin.map((x) => ({
182
- $ne: [`$$subdoc.${String(key)}`, toCorrectIdValue(x)],
183
- })),
184
- {},
185
- ];
210
+ toJSON(_, ret) {
211
+ if (this.options.privateFields) {
212
+ for (const key of this.options.privateFields) {
213
+ if (key in ret) {
214
+ delete ret[key];
215
+ }
216
+ }
186
217
  }
187
218
  }
188
- return [[], { [key]: toCorrectIdValue(value) }];
189
- }
190
- function toCorrectIdValue(v) {
191
- if (!v)
192
- return v;
193
- if (mongoose.isValidObjectId(v))
194
- return new mongoose.Types.ObjectId(v);
195
- return v;
196
- }
197
- function sortArrayToSortObject(arr, hasText) {
198
- const sortObj = {};
199
- for (const item of arr) {
200
- if (item === 'text' && hasText) {
201
- sortObj['score'] = { $meta: 'textScore' };
202
- }
203
- else if (item[0] === '-') {
204
- sortObj[item.substr(1)] = -1;
205
- }
206
- else if (item[0] === '+') {
207
- sortObj[item.substr(1)] = 1;
208
- }
209
- else {
210
- sortObj[item] = 1;
211
- }
219
+ populateDoc(doc, populates, subPath) {
220
+ return Promise.all(populates.map(async (populate) => {
221
+ try {
222
+ let subPathDoc;
223
+ if (subPath) {
224
+ subPathDoc = this._model.schema.subpaths[`${subPath}.${populate.path}`];
225
+ }
226
+ else {
227
+ subPathDoc = this._model.schema.paths[populate.path];
228
+ }
229
+ let ref = populate.ref || subPathDoc?.options.ref;
230
+ if (!ref && Array.isArray(subPathDoc?.options.type)) {
231
+ ref = subPathDoc.options.type[0].ref;
232
+ }
233
+ if (!ref) {
234
+ throw new Error(`ref was not defined in model with path ${populate.path}`);
235
+ }
236
+ const model = mongoose.model(ref);
237
+ await model.populate(doc, {
238
+ path: populate.path,
239
+ select: populate.select.join(' '),
240
+ ...(populate.populate ? { populate: populate.populate } : {}),
241
+ });
242
+ }
243
+ catch (e) {
244
+ console.error(e);
245
+ console.error({ doc, populates, path: subPath });
246
+ return Promise.resolve();
247
+ }
248
+ }));
212
249
  }
213
- return sortObj;
214
250
  }
@@ -0,0 +1,65 @@
1
+ import mongoose from 'mongoose';
2
+ import { Query } from './Query.js';
3
+ export interface IQueryOptionsPopulate<T extends any, K extends keyof T> {
4
+ path: K;
5
+ select: (T[K] extends object ? keyof T[K] : string)[];
6
+ ref?: string;
7
+ lookupRef?: string;
8
+ onFindOne?: boolean;
9
+ onPatch?: boolean;
10
+ onPost?: boolean;
11
+ onAll?: boolean;
12
+ onSearch?: boolean;
13
+ populate?: mongoose.PopulateOptions[];
14
+ }
15
+ interface IQuerySearchOptionsSub<T extends object, K extends keyof T> {
16
+ sub: K;
17
+ populate: IQueryOptionsPopulate<T[K], keyof T[K]>[];
18
+ }
19
+ interface IQueryOptions<T extends object> {
20
+ editFields?: (keyof T)[];
21
+ privateFields?: (keyof T)[];
22
+ query?: (keyof T)[];
23
+ select?: (keyof T)[];
24
+ defaultSelect?: (keyof T)[] | string[];
25
+ sort?: (keyof T)[];
26
+ populate?: IQueryOptionsPopulate<T, keyof T>[];
27
+ limit?: number;
28
+ subs?: IQuerySearchOptionsSub<T, keyof T>[];
29
+ updateDateKey?: keyof T;
30
+ }
31
+ export interface IQueryPopulate {
32
+ path: string;
33
+ select?: string[];
34
+ }
35
+ type IModelQuery = mongoose.QueryWithHelpers<unknown, unknown>;
36
+ export declare const toValidSelectRegexp: (select: string | number | symbol) => RegExp;
37
+ export declare const toValidSortRegexp: (sort: string | number | symbol) => RegExp;
38
+ export declare const toValidTextRegexp: (str: string) => RegExp | "";
39
+ export declare class QueryOptions<T extends object> {
40
+ private opts;
41
+ constructor(opts?: IQueryOptions<T>);
42
+ get publicFields(): (keyof T)[];
43
+ get privateFields(): (keyof T)[];
44
+ get populate(): IQueryOptionsPopulate<T, keyof T>[];
45
+ get subs(): IQuerySearchOptionsSub<T, keyof T>[];
46
+ get updateDateKey(): keyof T;
47
+ get query(): (keyof T)[];
48
+ createSearchQuery(query: Query<any, T>): mongoose.FilterQuery<T>;
49
+ setPopulate(modelQuery: IModelQuery, query: Query<T>): void;
50
+ getValidPopulate(queryPopulate: IQueryPopulate[], sub?: keyof T): IQueryOptionsPopulate<any, any>[];
51
+ setLimitAndSkip(modelQuery: IModelQuery, query: Query<T>): void;
52
+ setSelect(modelQuery: IModelQuery, query: Query<T>, overrideValid?: (keyof T)[]): void;
53
+ setSort(modelQuery: IModelQuery, query: Query<T>): void;
54
+ setProjection(modelQuery: IModelQuery, query: Query<T>): void;
55
+ getSubPopulateLookup<K extends keyof T>(query: Query<T>, sub: K): any[];
56
+ getSubFilterConditionAndMatch(subQuery: mongoose.FilterQuery<T>, sub: keyof T): {
57
+ $filter: {
58
+ input: string;
59
+ as: string;
60
+ cond: any;
61
+ };
62
+ $match: any;
63
+ };
64
+ }
65
+ export {};
@@ -0,0 +1,214 @@
1
+ import mongoose from 'mongoose';
2
+ import { DEFAULT_LIMIT } from './utils/constants.js';
3
+ export const toValidSelectRegexp = (select) => new RegExp(`^${String(select)}(\..|$)`);
4
+ export const toValidSortRegexp = (sort) => new RegExp(`^(\\+|-)?(${String(sort)}|text)$`);
5
+ export const toValidTextRegexp = (str) => typeof str === 'string'
6
+ ? new RegExp(str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i')
7
+ : '';
8
+ export class QueryOptions {
9
+ constructor(opts = {}) {
10
+ this.opts = opts;
11
+ }
12
+ get publicFields() {
13
+ return this.opts.editFields;
14
+ }
15
+ get privateFields() {
16
+ return this.opts.privateFields;
17
+ }
18
+ get populate() {
19
+ return this.opts.populate;
20
+ }
21
+ get subs() {
22
+ return this.opts.subs;
23
+ }
24
+ get updateDateKey() {
25
+ return this.opts.updateDateKey;
26
+ }
27
+ get query() {
28
+ return this.opts.query;
29
+ }
30
+ createSearchQuery(query) {
31
+ return query.createQuery({ noRoot: false, query: this.opts.query });
32
+ }
33
+ setPopulate(modelQuery, query) {
34
+ let populate = [];
35
+ if (query.populate.length > 0 && this.opts.populate) {
36
+ populate = this.getValidPopulate(query.populate).map((x) => ({
37
+ ...x,
38
+ select: x.select.join(' '),
39
+ }));
40
+ }
41
+ if (query.rootPopulate.length > 0) {
42
+ populate.push(...query.rootPopulate);
43
+ }
44
+ if (populate.length > 0) {
45
+ modelQuery.populate(populate);
46
+ }
47
+ }
48
+ getValidPopulate(queryPopulate, sub) {
49
+ let checkPop = this.opts.populate;
50
+ if (this.opts.subs && sub) {
51
+ const found = this.opts.subs.find((x) => x.sub === sub);
52
+ if (!found || !found.populate || found.populate.length === 0)
53
+ return [];
54
+ checkPop = found.populate;
55
+ }
56
+ if (!checkPop)
57
+ return [];
58
+ return queryPopulate
59
+ .map((pop) => {
60
+ const found = checkPop.find((x) => x.path === pop.path);
61
+ if (!found)
62
+ return null;
63
+ const select = pop.select?.filter((x) => found.select.includes(x)) || [];
64
+ return {
65
+ path: pop.path,
66
+ select: select.length > 0 ? select : found.select,
67
+ ...(found.populate ? { populate: found.populate } : {}),
68
+ };
69
+ })
70
+ .filter(Boolean);
71
+ }
72
+ setLimitAndSkip(modelQuery, query) {
73
+ if (query.export)
74
+ return;
75
+ modelQuery.skip(query.skip ?? 0);
76
+ modelQuery.limit(query.limit ?? this.opts.limit ?? DEFAULT_LIMIT);
77
+ }
78
+ setSelect(modelQuery, query, overrideValid) {
79
+ const valids = overrideValid || this.opts.select;
80
+ let selects = valids || [];
81
+ if (valids && valids.length > 0 && query.select.length > 0) {
82
+ selects = query.select.filter((select) => valids.some((valid) => String(select).match(toValidSelectRegexp(valid))));
83
+ }
84
+ else if (this.opts.defaultSelect) {
85
+ selects = this.opts.defaultSelect;
86
+ }
87
+ if (selects.length > 0) {
88
+ modelQuery.select(selects.join(' '));
89
+ }
90
+ }
91
+ setSort(modelQuery, query) {
92
+ if (query.sort.length > 0) {
93
+ if (this.opts.sort) {
94
+ const validSorts = query.sort.filter((x) => this.opts.sort.some((y) => String(x).match(toValidSortRegexp(y))));
95
+ modelQuery.sort(sortArrayToSortObject(validSorts, query.hasTextSearch));
96
+ }
97
+ else {
98
+ modelQuery.sort(sortArrayToSortObject(query.sort, query.hasTextSearch));
99
+ }
100
+ }
101
+ }
102
+ setProjection(modelQuery, query) {
103
+ if (query.projection) {
104
+ modelQuery.projection(query.projection);
105
+ query.projection = undefined;
106
+ }
107
+ }
108
+ getSubPopulateLookup(query, sub) {
109
+ if (!this.opts.subs)
110
+ return [];
111
+ const validPopulate = this.opts.subs.find((x) => x.sub === sub);
112
+ if (!validPopulate)
113
+ return [];
114
+ const populate = query.populate;
115
+ const $lookups = [];
116
+ if (populate.length > 0) {
117
+ for (const pop of populate) {
118
+ const found = validPopulate.populate.find((x) => x.path === pop.path);
119
+ if (!found)
120
+ continue;
121
+ const select = pop.select
122
+ ? found.select.filter((x) => pop.select.includes(String(x)))
123
+ : found.select;
124
+ $lookups.push(...[
125
+ {
126
+ $lookup: {
127
+ from: found.lookupRef || `${pop.path}s`,
128
+ localField: `${String(sub)}.${pop.path}`,
129
+ foreignField: '_id',
130
+ as: pop.path,
131
+ },
132
+ },
133
+ ...(pop.select
134
+ ? [
135
+ {
136
+ $project: {
137
+ _id: 1,
138
+ [sub]: 1,
139
+ count: 1,
140
+ [pop.path]: select.reduce((obj, item) => ({ ...obj, [item]: 1 }), {}),
141
+ },
142
+ },
143
+ ]
144
+ : []),
145
+ ]);
146
+ }
147
+ }
148
+ return $lookups;
149
+ }
150
+ getSubFilterConditionAndMatch(subQuery, sub) {
151
+ const cond = {};
152
+ let $match = {};
153
+ for (const key in subQuery) {
154
+ const v = subQuery[key];
155
+ if (key !== '$and' && !Array.isArray(v)) {
156
+ const $and = [];
157
+ const [newItem, toMatch] = queryToSubFilter(key, subQuery[key]);
158
+ if (newItem.length > 0) {
159
+ $and.push(...newItem);
160
+ }
161
+ $match = { ...$match, ...toMatch };
162
+ cond['$and'] = $and;
163
+ }
164
+ }
165
+ const $filter = { input: `$${String(sub)}`, as: 'subdoc', cond };
166
+ return { $filter, $match };
167
+ }
168
+ }
169
+ function queryToSubFilter(key, value) {
170
+ if (!value)
171
+ return [[], {}];
172
+ if (typeof value === 'object') {
173
+ if ('$in' in value && value.$in) {
174
+ return [
175
+ [{ $in: [`$$subdoc.${String(key)}`, value.$in.map(toCorrectIdValue)] }],
176
+ {},
177
+ ];
178
+ }
179
+ if ('$nin' in value && value.$nin) {
180
+ return [
181
+ value.$nin.map((x) => ({
182
+ $ne: [`$$subdoc.${String(key)}`, toCorrectIdValue(x)],
183
+ })),
184
+ {},
185
+ ];
186
+ }
187
+ }
188
+ return [[], { [key]: toCorrectIdValue(value) }];
189
+ }
190
+ function toCorrectIdValue(v) {
191
+ if (!v)
192
+ return v;
193
+ if (mongoose.isValidObjectId(v))
194
+ return new mongoose.Types.ObjectId(v);
195
+ return v;
196
+ }
197
+ function sortArrayToSortObject(arr, hasText) {
198
+ const sortObj = {};
199
+ for (const item of arr) {
200
+ if (item === 'text' && hasText) {
201
+ sortObj['score'] = { $meta: 'textScore' };
202
+ }
203
+ else if (item[0] === '-') {
204
+ sortObj[item.substr(1)] = -1;
205
+ }
206
+ else if (item[0] === '+') {
207
+ sortObj[item.substr(1)] = 1;
208
+ }
209
+ else {
210
+ sortObj[item] = 1;
211
+ }
212
+ }
213
+ return sortObj;
214
+ }
package/lib/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export * from './utils/index.js';
2
2
  export * from './QueryError.js';
3
3
  export * from './Query.js';
4
- export * from './QueryHandler.js';
5
- export * from './QueryHistory.js';
6
4
  export * from './QueryModel.js';
5
+ export * from './QueryHistory.js';
6
+ export * from './QueryOptions.js';
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export * from './utils/index.js';
2
2
  export * from './QueryError.js';
3
3
  export * from './Query.js';
4
- export * from './QueryHandler.js';
5
- export * from './QueryHistory.js';
6
4
  export * from './QueryModel.js';
5
+ export * from './QueryHistory.js';
6
+ export * from './QueryOptions.js';
@@ -5,9 +5,11 @@ export interface IMongooseQueryOptions {
5
5
  limit?: number | string;
6
6
  page?: number | string;
7
7
  text?: string;
8
+ $text?: string;
8
9
  sort?: string;
9
- populate?: string;
10
10
  select?: string;
11
+ populate?: string;
12
+ $populate?: string;
11
13
  [key: string]: string | number | undefined;
12
14
  }
13
15
  export declare function mongooseQueryOptions(query: IMongooseQueryOptions): {
@@ -1,4 +1,4 @@
1
- import { toValidTextRegexp } from '../QueryModel.js';
1
+ import { toValidTextRegexp } from '../QueryOptions.js';
2
2
  const VALUE_SPLIT = /,|\s/;
3
3
  const POPULATE_SPLIT = ';';
4
4
  const POPULATE_PATH_SPLIT = ':';
@@ -121,7 +121,7 @@ export function mongooseQueryWithOperation(query, key, str) {
121
121
  }
122
122
  export function greaterLessThanValue(key, query, str) {
123
123
  const [operation, field] = splitKey(key);
124
- let value = {};
124
+ let value;
125
125
  if (query[field]) {
126
126
  value = {
127
127
  ...query[field],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ewb/mongoose-query",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "type": "module",
5
5
  "description": "Parse queries and params to mongoose search. Strips dangerous keys and set corrects options with help of query values.",
6
6
  "main": "./lib/index.js",