nongoose 0.1.0-beta.1

ODM for MongoDB based on Mongoose
Documentation
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
mod builder;
pub(crate) mod globals;

pub use builder::NongooseBuilder;
use mongodb::{
  bson::{doc, Document},
  options::{CountOptions, FindOneOptions, FindOptions, UpdateOptions},
  results::UpdateResult,
  sync::Database,
};
#[cfg(feature = "tokio-runtime")]
use tokio::task::spawn_blocking;

use crate::{error::Result, Schema};

/// Nongoose instance
#[derive(Clone)]
#[non_exhaustive]
pub struct Nongoose {
  builder: NongooseBuilder,
}

impl Nongoose {
  /// Create a builder for building `Nongoose`. On the builder, call `.add_schema::<Schema>()` (Optional).
  /// Finally, call `.build()` to create an instance of `Nongoose`.
  pub fn builder(database: Database) -> NongooseBuilder {
    NongooseBuilder {
      database,
      schemas: Vec::new(),
    }
  }

  /// Shortcut for saving one document to the database. `Nongoose.create(doc)` does `Schema.save()`.
  ///
  /// This function triggers `Schema.save()`.
  ///
  /// # Example
  /// ```rust,no_run,ignore
  /// // Insert one new `User` document
  /// match nongoose.create::<User>(&user) {
  ///   Ok(user) => println!("User saved: {}", user.id),
  ///   Err(error) => eprintln!("Error saving the user: {}", error),
  /// }
  /// ```
  #[cfg(feature = "sync")]
  pub fn create<T>(&self, data: &T) -> Result<T>
  where
    T: Schema + Clone,
  {
    data.clone().save()
  }

  /// Shortcut for saving one document to the database. `Nongoose.create(doc)` does `Schema.save()`.
  ///
  /// This function triggers `Schema.save()`.
  ///
  /// # Example
  /// ```rust,no_run,ignore
  /// // Insert one new `User` document
  /// match nongoose.create::<User>(&user).await {
  ///   Ok(user) => println!("User saved: {}", user.id);,
  ///   Err(error) => eprintln!("Error saving the user: {}", error),
  /// }
  /// ```
  #[cfg(feature = "tokio-runtime")]
  pub async fn create<T>(&self, data: &T) -> Result<T>
  where
    T: Schema + Clone + Send + 'static,
  {
    data.clone().save().await
  }

  /// Counts number of documents that match `conditions` in a database collection.
  ///
  /// # Options
  /// ```rust,no_run,ignore
  /// CountOptions::builder()
  ///   // Optional (mongodb::options::Collation)
  ///   // The collation to use for the operation.
  ///   // See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more information on how to use this option.
  ///   .collation(...)
  ///   // Optional (mongodb::options::Hint)
  ///   // The index to use for the operation.
  ///   .hint(...)
  ///   // Optional (i64)
  ///   // The maximum number of documents to query. If a negative number is specified, the documents will be returned in a single batch limited in number
  ///   // by the positive value of the specified limit.
  ///   .limit(...)
  ///   // Optional (std::time::Duration)
  ///   // The maximum amount of time to allow the query to run.
  ///   // This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent across the wire as an integer number of milliseconds.
  ///   .max_time(...)
  ///   // Optional (mongodb::options::ReadConcern)
  ///   // The read concern to use for this find query.
  ///   // If none specified, the default set on the collection will be used.
  ///   .read_concern(...)
  ///   // Optional (mongodb::options::SelectionCriteria)
  ///   // The criteria used to select a server for this find query.
  ///   // If none specified, the default set on the collection will be used.
  ///   .selection_criteria(...)
  ///   // Optional (u64)
  ///   // The number of documents to skip before counting.
  ///   .skip(...)
  ///   // Required to create the instance of `CountOptions`
  ///   .build()
  /// ```
  ///
  /// # Example
  /// ```rust,no_run,ignore
  /// // Count users over 18 years of age
  /// match nongoose.count::<User>(doc! { "age": { "$gte": 18 } }, None) {
  ///   Ok(users) => println!("Found {} users!", users),
  ///   Err(error) => eprintln!("Error finding users: {}", error),
  /// }
  ///
  /// // Passing options
  /// match nongoose.count::<User>(
  ///   doc! { "age": { "$gte": 18 } },
  ///   Some(CountOptions::builder().limit(5).build())
  /// ) {
  ///   Ok(users) => println!("Found {} users!", users),
  ///   Err(error) => eprintln!("Error finding users: {}", error),
  /// }
  /// ```
  #[cfg(feature = "sync")]
  pub fn count<T>(&self, conditions: Document, options: Option<CountOptions>) -> Result<u64>
  where
    T: Schema,
  {
    self.builder.count_sync::<T>(conditions, options)
  }

  /// Counts number of documents that match `conditions` in a database collection.
  ///
  /// # Options
  /// ```rust,no_run,ignore
  /// CountOptions::builder()
  ///   // Optional (mongodb::options::Collation)
  ///   // The collation to use for the operation.
  ///   // See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more information on how to use this option.
  ///   .collation(...)
  ///   // Optional (mongodb::options::Hint)
  ///   // The index to use for the operation.
  ///   .hint(...)
  ///   // Optional (i64)
  ///   // The maximum number of documents to query. If a negative number is specified, the documents will be returned in a single batch limited in number
  ///   // by the positive value of the specified limit.
  ///   .limit(...)
  ///   // Optional (std::time::Duration)
  ///   // The maximum amount of time to allow the query to run.
  ///   // This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent across the wire as an integer number of milliseconds.
  ///   .max_time(...)
  ///   // Optional (mongodb::options::ReadConcern)
  ///   // The read concern to use for this find query.
  ///   // If none specified, the default set on the collection will be used.
  ///   .read_concern(...)
  ///   // Optional (mongodb::options::SelectionCriteria)
  ///   // The criteria used to select a server for this find query.
  ///   // If none specified, the default set on the collection will be used.
  ///   .selection_criteria(...)
  ///   // Optional (u64)
  ///   // The number of documents to skip before counting.
  ///   .skip(...)
  ///   // Required to create the instance of `CountOptions`
  ///   .build()
  /// ```
  ///
  /// # Example
  /// ```rust,no_run,ignore
  /// // Count users over 18 years of age
  /// match nongoose.count::<User>(doc! { "age": { "$gte": 18 } }, None).await {
  ///   Ok(users) => println!("Found {} users!", users),
  ///   Err(error) => eprintln!("Error finding users: {}", error),
  /// }
  ///
  /// // Passing options
  /// match nongoose
  ///   .count::<User>(
  ///     doc! { "age": { "$gte": 18 } },
  ///     Some(CountOptions::builder().limit(5).build())
  ///   )
  ///   .await
  /// {
  ///   Ok(users) => println!("Found {} users!", users),
  ///   Err(error) => eprintln!("Error finding users: {}", error),
  /// }
  /// ```
  #[cfg(feature = "tokio-runtime")]
  pub async fn count<T>(&self, conditions: Document, options: Option<CountOptions>) -> Result<u64>
  where
    T: Schema + Send + 'static,
  {
    let builder = self.builder.clone();
    spawn_blocking(move || builder.count_sync::<T>(conditions, options)).await?
  }

  /// Finds documents.
  ///
  /// # Options
  /// ```rust,no_run,ignore
  /// FindOptions::builder()
  ///   // Optional (bool)
  ///   // Enables writing to temporary files by the server. When set to true, the find operation can write data to the _tmp subdirectory in the dbPath directory.
  ///   // Only supported in server versions 4.4+.
  ///   .allow_disk_use(...)
  ///   // Optional (bool)
  ///   // If true, partial results will be returned from a mongos rather than an error being returned if one or more shards is down.
  ///   .allow_partial_results(...)
  ///   // Optional (u32)
  ///   // The number of documents the server should return per cursor batch.
  ///   // Note that this does not have any affect on the documents that are returned by a cursor, only the number of documents kept in memory at a given time
  ///   // (and by extension, the number of round trips needed to return the entire set of documents returned by the query.
  ///   .batch_size(...)
  ///   // Optional (String)
  ///   // Tags the query with an arbitrary string to help trace the operation through the database profiler, currentOp and logs.
  ///   .comment(...)
  ///   // Optional (mongodb::options::CursorType)
  ///   // The type of cursor to return.
  ///   .cursor_type(...)
  ///   // Optional (mongodb::options::Hint)
  ///   // The index to use for the operation.
  ///   .hint(...)
  ///   // Optional (i64)
  ///   // The maximum number of documents to query. If a negative number is specified, the documents will be returned in a single batch limited in number
  ///   // by the positive value of the specified limit.
  ///   .limit(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // The exclusive upper bound for a specific index.
  ///   .max(...)
  ///   // Optional (std::time::Duration)
  ///   // The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. If the cursor is not tailable, this option is ignored.
  ///   .max_await_time(...)
  ///   // Optional (u64)
  ///   // Maximum number of documents or index keys to scan when executing the query.
  ///   // Note: this option is deprecated starting in MongoDB version 4.0 and removed in MongoDB 4.2. Use the maxTimeMS option instead.
  ///   .max_scan(...)
  ///   // Optional (std::time::Duration)
  ///   // The maximum amount of time to allow the query to run.
  ///   // This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent across the wire as an integer number of milliseconds.
  ///   .max_time(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // The inclusive lower bound for a specific index.
  ///   .min(...)
  ///   // Optional (bool)
  ///   // Whether the server should close the cursor after a period of inactivity.
  ///   .no_cursor_timeout(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // Limits the fields of the document being returned.
  ///   .projection(...)
  ///   // Optional (mongodb::options::ReadConcern)
  ///   // The read concern to use for this find query.
  ///   // If none specified, the default set on the collection will be used.
  ///   .read_concern(...)
  ///   // Optional (bool)
  ///   // Whether to return only the index keys in the documents.
  ///   .return_key(...)
  ///   // Optional (mongodb::options::SelectionCriteria)
  ///   // The criteria used to select a server for this find query.
  ///   // If none specified, the default set on the collection will be used.
  ///   .selection_criteria(...)
  ///   // Optional (bool)
  ///   // Whether to return the record identifier for each document.
  ///   .show_record_id(...)
  ///   // Optional (u64)
  ///   // The number of documents to skip before counting.
  ///   .skip(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // The order of the documents for the purposes of the operation.
  ///   .sort(...)
  ///   // Optional (mongodb::options::Collation)
  ///   // The collation to use for the operation.
  ///   // See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more information on how to use this option.
  ///   .collation(...)
  ///   // Required to create the instance of `FindOptions`
  ///   .build()
  /// ```
  ///
  /// # Example
  /// ```rust,no_run,ignore
  /// // Search for users over 18 years of age
  /// match nongoose.find::<User>(doc! { "age": { "$gte": 18 } }, None) {
  ///   Ok(users) => println!("Found {} users!", users.len()),
  ///   Err(error) => eprintln!("Error finding users: {}", error),
  /// }
  ///
  /// // Passing options
  /// match nongoose.find::<User>(
  ///   doc! { "age": { "$gte": 18 } },
  ///   Some(FindOptions::builder().sort(doc! { "username": 1 }).build())
  /// ) {
  ///   Ok(users) => println!("Found {} users!", users.len()),
  ///   Err(error) => eprintln!("Error finding users: {}", error),
  /// }
  /// ```
  #[cfg(feature = "sync")]
  pub fn find<T>(&self, conditions: Document, options: Option<FindOptions>) -> Result<Vec<T>>
  where
    T: Schema,
  {
    self.builder.find_sync(conditions, options)
  }

  /// Finds documents.
  ///
  /// # Options
  /// ```rust,no_run,ignore
  /// FindOptions::builder()
  ///   // Optional (bool)
  ///   // Enables writing to temporary files by the server. When set to true, the find operation can write data to the _tmp subdirectory in the dbPath directory.
  ///   // Only supported in server versions 4.4+.
  ///   .allow_disk_use(...)
  ///   // Optional (bool)
  ///   // If true, partial results will be returned from a mongos rather than an error being returned if one or more shards is down.
  ///   .allow_partial_results(...)
  ///   // Optional (u32)
  ///   // The number of documents the server should return per cursor batch.
  ///   // Note that this does not have any affect on the documents that are returned by a cursor, only the number of documents kept in memory at a given time
  ///   // (and by extension, the number of round trips needed to return the entire set of documents returned by the query.
  ///   .batch_size(...)
  ///   // Optional (String)
  ///   // Tags the query with an arbitrary string to help trace the operation through the database profiler, currentOp and logs.
  ///   .comment(...)
  ///   // Optional (mongodb::options::CursorType)
  ///   // The type of cursor to return.
  ///   .cursor_type(...)
  ///   // Optional (mongodb::options::Hint)
  ///   // The index to use for the operation.
  ///   .hint(...)
  ///   // Optional (i64)
  ///   // The maximum number of documents to query. If a negative number is specified, the documents will be returned in a single batch limited in number
  ///   // by the positive value of the specified limit.
  ///   .limit(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // The exclusive upper bound for a specific index.
  ///   .max(...)
  ///   // Optional (std::time::Duration)
  ///   // The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. If the cursor is not tailable, this option is ignored.
  ///   .max_await_time(...)
  ///   // Optional (u64)
  ///   // Maximum number of documents or index keys to scan when executing the query.
  ///   // Note: this option is deprecated starting in MongoDB version 4.0 and removed in MongoDB 4.2. Use the maxTimeMS option instead.
  ///   .max_scan(...)
  ///   // Optional (std::time::Duration)
  ///   // The maximum amount of time to allow the query to run.
  ///   // This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent across the wire as an integer number of milliseconds.
  ///   .max_time(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // The inclusive lower bound for a specific index.
  ///   .min(...)
  ///   // Optional (bool)
  ///   // Whether the server should close the cursor after a period of inactivity.
  ///   .no_cursor_timeout(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // Limits the fields of the document being returned.
  ///   .projection(...)
  ///   // Optional (mongodb::options::ReadConcern)
  ///   // The read concern to use for this find query.
  ///   // If none specified, the default set on the collection will be used.
  ///   .read_concern(...)
  ///   // Optional (bool)
  ///   // Whether to return only the index keys in the documents.
  ///   .return_key(...)
  ///   // Optional (mongodb::options::SelectionCriteria)
  ///   // The criteria used to select a server for this find query.
  ///   // If none specified, the default set on the collection will be used.
  ///   .selection_criteria(...)
  ///   // Optional (bool)
  ///   // Whether to return the record identifier for each document.
  ///   .show_record_id(...)
  ///   // Optional (u64)
  ///   // The number of documents to skip before counting.
  ///   .skip(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // The order of the documents for the purposes of the operation.
  ///   .sort(...)
  ///   // Optional (mongodb::options::Collation)
  ///   // The collation to use for the operation.
  ///   // See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more information on how to use this option.
  ///   .collation(...)
  ///   // Required to create the instance of `FindOptions`
  ///   .build()
  /// ```
  ///
  /// See more [here](https://docs.rs/mongodb/2.0.1/mongodb/options/struct.FindOptions.html)
  ///
  /// # Example
  /// ```rust,no_run,ignore
  /// // Search for users over 18 years of age
  /// match nongoose.find::<User>(doc! { "age": { "$gte": 18 } }, None).await {
  ///   Ok(users) => println!("Found {} users!", users.len()),
  ///   Err(error) => eprintln!("Error finding users: {}", error),
  /// }
  ///
  /// // Passing options
  /// match nongoose.find::<User>(
  ///   doc! { "age": { "$gte": 18 } },
  ///   Some(FindOptions::builder().sort(doc! { "username": 1 }).build())
  /// ).await {
  ///   Ok(users) => println!("Found {} users!", users.len()),
  ///   Err(error) => eprintln!("Error finding users: {}", error),
  /// }
  /// ```
  #[cfg(feature = "tokio-runtime")]
  pub async fn find<T>(&self, conditions: Document, options: Option<FindOptions>) -> Result<Vec<T>>
  where
    T: Schema + 'static,
  {
    let builder = self.builder.clone();
    spawn_blocking(move || builder.find_sync(conditions, options)).await?
  }

  /// Finds a single document by its `_id` field. `find_by_id(id)`is almost equivalent to `find_one(doc! { "_id": id })`.
  /// If you want to query by a document's `_id`, use `find_by_id()`instead of `find_one()`.
  ///
  /// This function triggers `find_one()`.
  ///
  /// # Example
  /// ```rust,no_run,ignore
  /// // Find one `User` document by `_id`
  /// match nongoose.find_by_id::<User>(&ObjectId::parse_str("616c91dc8cb70be8cc7d1f38").unwrap()) {
  ///   Ok(Some(user)) => println!("User found: {}", user.id),
  ///   Ok(None) => eprintln!("Cannot find the user"),
  ///   Err(error) => eprintln!("Error finding user: {}", error),
  /// }
  /// ```
  #[cfg(feature = "sync")]
  pub fn find_by_id<T>(&self, id: &T::Id) -> Result<Option<T>>
  where
    T: Schema,
  {
    self.find_one(doc! { "_id": id.clone().into() }, None)
  }

  /// Finds a single document by its `_id` field. `find_by_id(id)`is almost equivalent to `find_one(doc! { "_id": id })`.
  /// If you want to query by a document's `_id`, use `find_by_id()`instead of `find_one()`.
  ///
  /// This function triggers `find_one()`.
  ///
  /// # Example
  /// ```rust,no_run,ignore
  /// // Find one `User` document by `_id`
  /// match nongoose.find_by_id::<User>(&ObjectId::parse_str("616c91dc8cb70be8cc7d1f38").unwrap()).await {
  ///   Ok(Some(user)) => println!("User found: {}", user.id),
  ///   Ok(None) => eprintln!("Cannot find the user"),
  ///   Err(error) => eprintln!("Error finding user: {}", error),
  /// }
  /// ```
  #[cfg(feature = "tokio-runtime")]
  pub async fn find_by_id<T>(&self, id: &T::Id) -> Result<Option<T>>
  where
    T: Schema + 'static,
  {
    self.find_one(doc! { "_id": id.clone().into() }, None).await
  }

  /// Finds one document.
  ///
  /// # Options
  /// ```rust,no_run,ignore
  /// FindOneOptions::builder()
  ///   // Optional (bool)
  ///   // If true, partial results will be returned from a mongos rather than an error being returned if one or more shards is down.
  ///   .allow_partial_results(...)
  ///   // Optional (mongodb::options::Collation)
  ///   // The collation to use for the operation.
  ///   // See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more information on how to use this option.
  ///   .collation(...)
  ///   // Optional (String)
  ///   // Tags the query with an arbitrary string to help trace the operation through the database profiler, currentOp and logs.
  ///   .comment(...)
  ///   // Optional (mongodb::options::Hint)
  ///   // The index to use for the operation.
  ///   .hint(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // The exclusive upper bound for a specific index.
  ///   .max(...)
  ///   // Optional (u64)
  ///   // Maximum number of documents or index keys to scan when executing the query.
  ///   // Note: this option is deprecated starting in MongoDB version 4.0 and removed in MongoDB 4.2. Use the maxTimeMS option instead.
  ///   .max_scan(...)
  ///   // Optional (std::time::Duration)
  ///   // The maximum amount of time to allow the query to run.
  ///   // This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent across the wire as an integer number of milliseconds.
  ///   .max_time(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // The inclusive lower bound for a specific index.
  ///   .min(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // Limits the fields of the document being returned.
  ///   .projection(...)
  ///   // Optional (mongodb::options::ReadConcern)
  ///   // The read concern to use for this find query.
  ///   // If none specified, the default set on the collection will be used.
  ///   .read_concern(...)
  ///   // Optional (bool)
  ///   // Whether to return only the index keys in the documents.
  ///   .return_key(...)
  ///   // Optional (mongodb::options::SelectionCriteria)
  ///   // The criteria used to select a server for this find query.
  ///   // If none specified, the default set on the collection will be used.
  ///   .selection_criteria(...)
  ///   // Optional (bool)
  ///   // Whether to return the record identifier for each document.
  ///   .show_record_id(...)
  ///   // Optional (u64)
  ///   // The number of documents to skip before counting.
  ///   .skip(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // The order of the documents for the purposes of the operation.
  ///   .sort(...)
  ///   // Required to create the instance of `FindOneOptions`
  ///   .build()
  /// ```
  ///
  /// # Example
  /// ```rust,no_run,ignore
  /// // Find one user whose `username` is `nongoose`
  /// match nongoose.find_one::<User>(doc! { "username": "nongoose" }, None) {
  ///   Ok(Some(user)) => println!("User found: {}", user.id),
  ///   Ok(None) => eprintln!("Cannot find the user"),
  ///   Err(error) => eprintln!("Error finding user: {}", error),
  /// }
  ///
  /// // Passing options
  /// match nongoose.find_one::<User>(
  ///   doc! { "username": "nongoose" },
  ///   Some(FindOneOptions::builder().sort(doc! { "username": 1 }).build())
  /// ) {
  ///   Ok(Some(user)) => println!("User found: {}", user.id),
  ///   Ok(None) => eprintln!("Cannot find the user"),
  ///   Err(error) => eprintln!("Error finding user: {}", error),
  /// }
  /// ```
  #[cfg(feature = "sync")]
  pub fn find_one<T>(
    &self,
    conditions: Document,
    options: Option<FindOneOptions>,
  ) -> Result<Option<T>>
  where
    T: Schema,
  {
    self.builder.find_one_sync(conditions, options)
  }

  /// Finds one document.
  ///
  /// # Options
  /// ```rust,no_run,ignore
  /// FindOneOptions::builder()
  ///   // Optional (bool)
  ///   // If true, partial results will be returned from a mongos rather than an error being returned if one or more shards is down.
  ///   .allow_partial_results(...)
  ///   // Optional (mongodb::options::Collation)
  ///   // The collation to use for the operation.
  ///   // See the [documentation](https://docs.mongodb.com/manual/reference/collation/) for more information on how to use this option.
  ///   .collation(...)
  ///   // Optional (String)
  ///   // Tags the query with an arbitrary string to help trace the operation through the database profiler, currentOp and logs.
  ///   .comment(...)
  ///   // Optional (mongodb::options::Hint)
  ///   // The index to use for the operation.
  ///   .hint(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // The exclusive upper bound for a specific index.
  ///   .max(...)
  ///   // Optional (u64)
  ///   // Maximum number of documents or index keys to scan when executing the query.
  ///   // Note: this option is deprecated starting in MongoDB version 4.0 and removed in MongoDB 4.2. Use the maxTimeMS option instead.
  ///   .max_scan(...)
  ///   // Optional (std::time::Duration)
  ///   // The maximum amount of time to allow the query to run.
  ///   // This options maps to the `maxTimeMS` MongoDB query option, so the duration will be sent across the wire as an integer number of milliseconds.
  ///   .max_time(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // The inclusive lower bound for a specific index.
  ///   .min(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // Limits the fields of the document being returned.
  ///   .projection(...)
  ///   // Optional (mongodb::options::ReadConcern)
  ///   // The read concern to use for this find query.
  ///   // If none specified, the default set on the collection will be used.
  ///   .read_concern(...)
  ///   // Optional (bool)
  ///   // Whether to return only the index keys in the documents.
  ///   .return_key(...)
  ///   // Optional (mongodb::options::SelectionCriteria)
  ///   // The criteria used to select a server for this find query.
  ///   // If none specified, the default set on the collection will be used.
  ///   .selection_criteria(...)
  ///   // Optional (bool)
  ///   // Whether to return the record identifier for each document.
  ///   .show_record_id(...)
  ///   // Optional (u64)
  ///   // The number of documents to skip before counting.
  ///   .skip(...)
  ///   // Optional (mongodb::bson::Document)
  ///   // The order of the documents for the purposes of the operation.
  ///   .sort(...)
  ///   // Required to create the instance of `FindOneOptions`
  ///   .build()
  /// ```
  ///
  /// # Example
  /// ```rust,no_run,ignore
  /// // Find one user whose `username` is `nongoose`
  /// match nongoose.find_one::<User>(doc! { "username": "nongoose" }, None).await {
  ///   Ok(Some(user)) => println!("User found: {}", user.id),
  ///   Ok(None) => eprintln!("Cannot find the user"),
  ///   Err(error) => eprintln!("Error finding user: {}", error),
  /// }
  ///
  /// // Passing options
  /// match nongoose.find_one::<User>(
  ///   doc! { "username": "nongoose" },
  ///   Some(FindOneOptions::builder().sort(doc! { "username": 1 }).build())
  /// ).await {
  ///   Ok(Some(user)) => println!("User found: {}", user.id),
  ///   Ok(None) => eprintln!("Cannot find the user"),
  ///   Err(error) => eprintln!("Error finding user: {}", error),
  /// }
  /// ```
  #[cfg(feature = "tokio-runtime")]
  pub async fn find_one<T>(
    &self,
    conditions: Document,
    options: Option<FindOneOptions>,
  ) -> Result<Option<T>>
  where
    T: Schema + 'static,
  {
    let builder = self.builder.clone();
    spawn_blocking(move || builder.find_one_sync(conditions, options)).await?
  }

  /// Updates _all_ documents in the database that match `conditions` without returning them.
  ///
  /// **Note** update_many will _not_ fire update middleware (`SchemaBefore::before_update()`).
  ///
  /// # Options
  /// ```rust,no_run,ignore
  /// UpdateOptions::builder()
  ///   // Optional (Vec<mongodb::bson::Document>)
  ///   // A set of filters specifying to which array elements an update should apply.
  ///   // See the documentation [here](https://docs.mongodb.com/manual/reference/command/update/) for more information on array filters.
  ///   .array_filters(...)
  ///   // Optional (bool)
  ///   // Opt out of document-level validation.
  ///   .bypass_document_validation(...)
  ///   // Optional (bool)
  ///   // If true, insert a document if no matching document is found.
  ///   .upsert(...)
  ///   // Optional (mongodb::options::Collation)
  ///   // The collation to use for the operation.
  ///   .collation(...)
  ///   // Optional (mongodb::options::Hint)
  ///   // A document or string that specifies the index to use to support the query predicate.
  ///   // Only available in MongoDB 4.2+. See the official MongoDB [documentation](https://docs.mongodb.com/manual/reference/command/update/#ex-update-command-hint) for examples.
  ///   .hint(...)
  ///   // Optional (mongodb::options::WriteConcern)
  ///   // The write concern for the operation.
  ///   .write_concern(...)
  ///   // Required to create the instance of `UpdateOptions`
  ///   .build()
  /// ```
  ///
  /// # Example
  /// ```rust,no_run,ignore
  /// // Update the age to 18 if it is under 18
  /// match nongoose.update_many::<User>(
  ///   doc! { "age": { "$lt": 18 } },
  ///   doc! { "$set": { "age": 18 } },
  ///   None
  /// ) {
  ///   Ok(result) => println!("Modified {} documents", result.modified_count),
  ///   Err(error) => eprintln!("Error updating users: {}", error),
  /// }
  /// ```
  #[cfg(feature = "sync")]
  pub fn update_many<T>(
    &self,
    conditions: Document,
    data: Document,
    options: Option<UpdateOptions>,
  ) -> Result<UpdateResult>
  where
    T: Schema,
  {
    self
      .builder
      .update_many_sync::<T>(conditions, data, options)
  }

  /// Updates _all_ documents in the database that match `conditions` without returning them.
  ///
  /// **Note** update_many will _not_ fire update middleware (`SchemaBefore::before_update()`).
  ///
  /// # Options
  /// ```rust,no_run,ignore
  /// UpdateOptions::builder()
  ///   // Optional (Vec<mongodb::bson::Document>)
  ///   // A set of filters specifying to which array elements an update should apply.
  ///   // See the documentation [here](https://docs.mongodb.com/manual/reference/command/update/) for more information on array filters.
  ///   .array_filters(...)
  ///   // Optional (bool)
  ///   // Opt out of document-level validation.
  ///   .bypass_document_validation(...)
  ///   // Optional (bool)
  ///   // If true, insert a document if no matching document is found.
  ///   .upsert(...)
  ///   // Optional (mongodb::options::Collation)
  ///   // The collation to use for the operation.
  ///   .collation(...)
  ///   // Optional (mongodb::options::Hint)
  ///   // A document or string that specifies the index to use to support the query predicate.
  ///   // Only available in MongoDB 4.2+. See the official MongoDB [documentation](https://docs.mongodb.com/manual/reference/command/update/#ex-update-command-hint) for examples.
  ///   .hint(...)
  ///   // Optional (mongodb::options::WriteConcern)
  ///   // The write concern for the operation.
  ///   .write_concern(...)
  ///   // Required to create the instance of `UpdateOptions`
  ///   .build()
  /// ```
  ///
  /// # Example
  /// ```rust,no_run,ignore
  /// // Update the age to 18 if it is under 18
  /// match nongoose.update_many::<User>(
  ///   doc! { "age": { "$lt": 18 } },
  ///   doc! { "$set": { "age": 18 } },
  ///   None
  /// ).await {
  ///   Ok(result) => println!("Modified {} documents", result.modified_count),
  ///   Err(error) => eprintln!("Error updating users: {}", error),
  /// }
  /// ```
  #[cfg(feature = "tokio-runtime")]
  pub async fn update_many<T>(
    &self,
    conditions: Document,
    data: Document,
    options: Option<UpdateOptions>,
  ) -> Result<UpdateResult>
  where
    T: Schema + 'static,
  {
    let builder = self.builder.clone();
    spawn_blocking(move || builder.update_many_sync::<T>(conditions, data, options)).await?
  }
}