-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
middleware.ts
70 lines (53 loc) · 1.72 KB
/
middleware.ts
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
import { Schema, model, Model, Document, SaveOptions, Query, Aggregate } from 'mongoose';
const schema: Schema = new Schema({ name: { type: 'String' } });
schema.pre<Query<any, any>>('find', async function() {
console.log('Find', this.getFilter());
});
schema.pre<Query<any, any>>('find', async function() {
console.log('Find', this.notAFunction());
});
schema.pre<Aggregate<any>>('aggregate', async function() {
console.log('Pipeline', this.pipeline());
});
schema.post<Aggregate<any>>('aggregate', async function(res: Array<any>) {
console.log('Pipeline', this.pipeline(), res[0]);
});
schema.pre(['save', 'validate'], { query: false, document: true }, async function applyChanges() {
await Test.findOne({});
});
schema.pre('save', function(next, opts: SaveOptions) {
console.log(opts.session);
next();
});
interface ITest extends Document {
name?: string;
}
schema.pre('save', function(next) {
console.log(this.name);
});
schema.post<ITest>('save', function() {
console.log(this.name);
});
schema.post<ITest>('save', function(err: Error, res: ITest, next: Function) {
console.log(this.name, err.stack);
});
schema.pre<Model<ITest>>('insertMany', function() {
const name: string = this.name;
return Promise.resolve();
});
schema.pre<Model<ITest>>('insertMany', { document: false, query: false }, function() {
console.log(this.name);
});
schema.pre<Model<ITest>>('insertMany', function(next) {
console.log(this.name);
next();
});
schema.pre<Model<ITest>>('insertMany', function(next, doc: ITest) {
console.log(this.name, doc);
next();
});
schema.pre<Model<ITest>>('insertMany', function(next, docs: Array<ITest>) {
console.log(this.name, docs);
next();
});
const Test = model<ITest>('Test', schema);