deno.land / x / mongoose@6.7.5 / test / types / models.test.ts

models.test.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
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
import { ObjectId } from 'bson';import { Schema, Document, Model, connection, model, Types, UpdateQuery, CallbackError, HydratedDocument, HydratedDocumentFromSchema, Query, UpdateWriteOpResult} from 'mongoose';import { expectAssignable, expectError, expectType } from 'tsd';import { AutoTypedSchemaType, autoTypedSchema } from './schema.test';import { UpdateOneModel } from 'mongodb';
function conventionalSyntax(): void { interface ITest extends Document { foo: string; }
const TestSchema = new Schema<ITest>({ foo: { type: String, required: true } });
const Test = connection.model<ITest>('Test', TestSchema);
const bar = (SomeModel: Model<ITest>) => console.log(SomeModel);
bar(Test);
const doc = new Test({ foo: '42' }); console.log(doc.foo); doc.save();
expectError(new Test<{ foo: string }>({}));}
function rawDocSyntax(): void { interface ITest { foo: string; }
interface ITestMethods { bar(): number; }
type TestModel = Model<ITest, {}, ITestMethods>;
const TestSchema = new Schema<ITest, TestModel>({ foo: { type: String, required: true } });
const Test = connection.model<ITest, TestModel>('Test', TestSchema);
expectType<Model<ITest, {}, ITestMethods, {}>>(Test);
const doc = new Test({ foo: '42' }); console.log(doc.foo); console.log(doc.bar()); doc.save();}
function tAndDocSyntax(): void { interface ITest { id: number; foo: string; }
const TestSchema = new Schema<ITest & Document>({ foo: { type: String, required: true } });
const Test = connection.model<ITest & Document>('Test', TestSchema);
const aggregated: Promise<Document> = Test.aggregate([]).then(res => res[0]);
const bar = (SomeModel: Model<ITest & Document>) => console.log(SomeModel);}
async function insertManyTest() { interface ITest { foo: string; }
const TestSchema = new Schema<ITest & Document>({ foo: { type: String, required: true } });
const Test = connection.model<ITest & Document>('Test', TestSchema);
Test.insertMany([{ foo: 'bar' }]).then(async res => { res.length; });
const res = await Test.insertMany([{ foo: 'bar' }], { rawResult: true }); expectType<ObjectId>(res.insertedIds[0]);}
function schemaStaticsWithoutGenerics() { const UserSchema = new Schema({}); UserSchema.statics.static1 = function() { return ''; };
interface IUserDocument extends Document { instanceField: string; } interface IUserModel extends Model<IUserDocument> { static1: () => string; }
const UserModel: IUserModel = model<IUserDocument, IUserModel>('User', UserSchema); UserModel.static1();}
function gh10074() { interface IDog { breed: string; name: string; age: number; }
type IDogDocument = IDog & Document;
const DogSchema = new Schema<IDogDocument>( { breed: { type: String }, name: { type: String }, age: { type: Number } } );
const Dog = model<IDogDocument, Model<IDogDocument>>('dog', DogSchema);
const rex = new Dog({ breed: 'test', name: 'rex', age: '50' });}
async function gh10359() { interface Group { groupId: string; }
interface User extends Group { firstName: string; lastName: string; }
async function foo(model: Model<User, {}, {}, {}>) { const doc = await model.findOne({ groupId: 'test' }).lean().exec(); expectType<string | undefined>(doc?.firstName); expectType<string | undefined>(doc?.lastName); expectType<Types.ObjectId | undefined>(doc?._id); expectType<string | undefined>(doc?.groupId); return doc; }
const UserModel = model<User>('gh10359', new Schema({ firstName: String, lastName: String, groupId: String })); foo(UserModel);}
const ExpiresSchema = new Schema({ ttl: { type: Date, expires: 3600 }});
interface IProject extends Document { name: string; myMethod(): number;}
interface ProjectModel extends Model<IProject> { myStatic(): number;}
const projectSchema = new Schema<IProject, ProjectModel>({ name: String });
projectSchema.pre('save', function() { // this => IProject});
projectSchema.post('save', function() { // this => IProject});
projectSchema.pre('deleteOne', function() { this.model;});
projectSchema.post('deleteOne', function() { this.model;});
projectSchema.methods.myMethod = () => 10;
projectSchema.statics.myStatic = () => 42;
const Project = connection.model<IProject, ProjectModel>('Project', projectSchema);Project.myStatic();
Project.create({ name: 'mongoose'}).then(project => { project.myMethod();});

Project.exists({ name: 'Hello' }).then(result => { result?._id;});Project.exists({ name: 'Hello' }, (err, result) => { result?._id;});
function find() { // no args Project.find();
// just filter Project.find({}); Project.find({ name: 'Hello' });
// just callback Project.find((error: CallbackError, result: IProject[]) => console.log(error, result));
// filter + projection Project.find({}, undefined); Project.find({}, null); Project.find({}, { name: 1 }); Project.find({}, { name: 0 });
// filter + callback Project.find({}, (error: CallbackError, result: IProject[]) => console.log(error, result)); Project.find({ name: 'Hello' }, (error: CallbackError, result: IProject[]) => console.log(error, result));
// filter + projection + options Project.find({}, undefined, { limit: 5 }); Project.find({}, null, { limit: 5 }); Project.find({}, { name: 1 }, { limit: 5 });
// filter + projection + options + callback Project.find({}, undefined, { limit: 5 }, (error: CallbackError, result: IProject[]) => console.log(error, result)); Project.find({}, null, { limit: 5 }, (error: CallbackError, result: IProject[]) => console.log(error, result)); Project.find({}, { name: 1 }, { limit: 5 }, (error: CallbackError, result: IProject[]) => console.log(error, result));}
function inheritance() { class InteractsWithDatabase extends Model { async _update(): Promise<void> { await this.save(); } }
class SourceProvider extends InteractsWithDatabase { static async deleteInstallation(installationId: number): Promise<void> { await this.findOneAndDelete({ installationId }); } }}
Project.createCollection({ expires: '5 seconds' });Project.createCollection({ expireAfterSeconds: 5 });expectError(Project.createCollection({ expireAfterSeconds: '5 seconds' }));
function bulkWrite() {
const schema = new Schema({ str: { type: String, default: 'test' }, num: Number });
const M = model('Test', schema);
const ops = [ { updateOne: { filter: { num: 0 }, update: { $inc: { num: 1 } }, upsert: true } } ]; M.bulkWrite(ops);}
function bulkWriteAddToSet() { const schema = new Schema({ arr: [String] });
const M = model('Test', schema);
const ops = [ { updateOne: { filter: { arr: { $nin: ['abc'] } }, update: { $addToSet: { arr: 'abc' } } } } ];
return M.bulkWrite(ops);}
async function gh12277() { type DocumentType<T> = Document<any, any, T> & T;
interface BaseModelClassDoc { firstname: string; }
const baseModelClassSchema = new Schema({ firstname: String });
const BaseModel = model<DocumentType<BaseModelClassDoc>>('test', baseModelClassSchema);
await BaseModel.bulkWrite([ { updateOne: { update: { firstname: 'test' }, filter: { firstname: 'asdsd' } } } ]);}
export function autoTypedModel() { const AutoTypedSchema = autoTypedSchema(); const AutoTypedModel = model('AutoTypeModel', AutoTypedSchema);
(async() => { // Model-functions-test // Create should works with arbitrary objects. const randomObject = await AutoTypedModel.create({ unExistKey: 'unExistKey', description: 'st' }); expectType<AutoTypedSchemaType['schema']['userName']>(randomObject.userName);
const testDoc1 = await AutoTypedModel.create({ userName: 'M0_0a' }); expectType<AutoTypedSchemaType['schema']['userName']>(testDoc1.userName); expectType<AutoTypedSchemaType['schema']['description']>(testDoc1.description);
const testDoc2 = await AutoTypedModel.insertMany([{ userName: 'M0_0a' }]); expectType<AutoTypedSchemaType['schema']['userName']>(testDoc2[0].userName); expectType<AutoTypedSchemaType['schema']['description'] | undefined>(testDoc2[0]?.description);
const testDoc3 = await AutoTypedModel.findOne({ userName: 'M0_0a' }); expectType<AutoTypedSchemaType['schema']['userName'] | undefined>(testDoc3?.userName); expectType<AutoTypedSchemaType['schema']['description'] | undefined>(testDoc3?.description);
// Model-statics-functions-test expectType<ReturnType<AutoTypedSchemaType['statics']['staticFn']>>(AutoTypedModel.staticFn());
})(); return AutoTypedModel;}
function gh11911() { interface IAnimal { name?: string; }
const animalSchema = new Schema<IAnimal>({ name: { type: String } });
const Animal = model<IAnimal>('Animal', animalSchema);
const changes: UpdateQuery<IAnimal> = {}; expectAssignable<UpdateOneModel>({ filter: {}, update: changes });}

function gh12059() { interface IAnimal { name?: string; }
const animalSchema = new Schema<IAnimal>({ name: { type: String } });
const Animal = model<IAnimal>('Animal', animalSchema); const animal = new Animal();
Animal.bulkSave([animal], { timestamps: false }); Animal.bulkSave([animal], { timestamps: true }); Animal.bulkSave([animal], {});}
function schemaInstanceMethodsAndQueryHelpers() { type UserModelQuery = Query<any, HydratedDocument<User>, UserQueryHelpers> & UserQueryHelpers; interface UserQueryHelpers { byName(this: UserModelQuery, name: string): this } interface User { name: string; } interface UserInstanceMethods { doSomething(this: HydratedDocument<User>): string; } interface UserStaticMethods { findByName(name: string): Promise<HydratedDocument<User>>; } type UserModel = Model<User, UserQueryHelpers, UserInstanceMethods> & UserStaticMethods;
const userSchema = new Schema<User, UserModel, UserInstanceMethods, UserQueryHelpers, any, UserStaticMethods>({ name: String }, { statics: { findByName(name: string) { return model('User').findOne({ name }).orFail(); } }, methods: { doSomething() { return 'test'; } }, query: { byName(this: UserModelQuery, name: string) { return this.where({ name }); } } });
const TestModel = model<User, UserModel, UserQueryHelpers>('User', userSchema);}
function gh12100() { const schema = new Schema();
const Model = model('Model', schema);
Model.syncIndexes({ continueOnError: true, noResponse: true }); Model.syncIndexes({ continueOnError: false, noResponse: true });}
(function gh12070() { const schema_with_string_id = new Schema({ _id: String, nickname: String }); const TestModel = model('test', schema_with_string_id); const obj = new TestModel();
expectType<string>(obj._id);})();
(async function gh12094() { const userSchema = new Schema({ name: { type: String, required: true }, email: { type: String, required: true }, avatar: String });
const User = model('User', userSchema);
const doc = await User.exists({ name: 'Bill' }).orFail(); expectType<Types.ObjectId>(doc._id);})();

function modelRemoveOptions() { const cmodel = model('Test', new Schema());
cmodel.remove({}, {});}
async function gh12286() { interface IUser{ name: string; } const schema = new Schema<IUser>({ name: { type: String, required: true } });
const User = model<IUser>('User', schema);
const user = await User.findById('0'.repeat(24), { name: 1 }).lean(); expectType<string | undefined>(user?.name);}

function gh12332() { interface IUser{ age: number } const schema = new Schema<IUser>({ age: Number });
const User = model<IUser>('User', schema);
User.castObject({ age: '19' }); User.castObject({ age: '19' }, { ignoreCastErrors: true });}
async function gh12347() { interface IUser{ name: string; } const schema = new Schema<IUser>({ name: { type: String, required: true } });
const User = model<IUser>('User', schema);
const replaceOneResult = await User.replaceOne({}, {}); expectType<UpdateWriteOpResult>(replaceOneResult);}
async function gh12319() { const projectSchema = new Schema( { name: { type: String, required: true } }, { methods: { async doSomething() { } } } );
const ProjectModel = model('Project', projectSchema);
type ProjectModelHydratedDoc = HydratedDocumentFromSchema< typeof projectSchema >;
expectType<ProjectModelHydratedDoc>(await ProjectModel.findOne().orFail());}
function findWithId() { const id = new Types.ObjectId(); const TestModel = model('test', new Schema({})); TestModel.find(id); TestModel.findOne(id);}
function gh12573ModelAny() { const TestModel = model<any>('Test', new Schema({})); const doc = new TestModel(); expectType<any>(doc); const { fieldA } = doc; expectType<any>(fieldA);}
mongoose

Version Info

Tagged at
a year ago