-
Notifications
You must be signed in to change notification settings - Fork 2
/
mongoDatabase.js
4415 lines (3991 loc) · 111 KB
/
mongoDatabase.js
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const {MongoClient, ObjectID} = require('mongodb')
const bcrypt = require('bcryptjs')
require('dotenv').config()
const nodemailer = require('nodemailer')
const url = process.env.MONGO_DB_URL
const client = new MongoClient(url, {useUnifiedTopology: true, useNewUrlParser: true})
module.exports = async function() {
await client.connect()
const db = client.db()
const users = db.collection('users')
const images = db.collection('images')
const audios = db.collection('audios')
const videos = db.collection('videos')
const tags = db.collection('tags')
const categories = db.collection('categories')
const locations = db.collection('locations')
const revisions = db.collection('revisions')
const plants = db.collection('plants')
const waypoints = db.collection('waypoints')
const tours = db.collection('tours')
const learn_more = db.collection('learn_more')
//Users
//Get all user
//GET /api/users
async function getUsers() {
return await users.find().toArray()
}
//Create new user, use for register
//Takes in email, username and password, role default to Manager
//POST /api/users
async function createUser({email, user_name, password, role="Manager"}) {
//Check if email or username is repeating
const user = await users.findOne({
$or: [{email: email}, {user_name: user_name}]
})
if (user) {
throw Error("Username or email is already taken")
}
if (!email) { //email can't be null
throw Error("Requires an email")
}
if (typeof email === 'string' || email instanceof String) {
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
if(!(re.test(email.toLowerCase()))) {
throw Error("Incorrectly formatted email")
}
} else {
throw Error("Invalid input for email")
}
if (!user_name) {
throw Error("Requires an user name")
}
if (!(typeof user_name === 'string' || user_name instanceof String)) {
throw Error("Invalid input for user_name")
}
if (!password) { //password can't be null
throw Error("Requires a password")
}
if (!(typeof password === 'string' || password instanceof String)) {
throw Error("Invalid input for password")
}
if (typeof role === 'string' || role instanceof String) {
if (!(role === 'Manager' || role === 'Admin')) {
throw Error("Invalid role, role must be Manager or Admin")
}
} else {
throw Error("Invalid input for role")
}
//Hash password
const encrypted = await bcrypt.hash(password, 12)
const result = await users.insertOne({
email,
user_name,
password: encrypted,
role
})
//Need this to make jwt token later
return result
}
//Get One user, use for login
//Takes in email/username and password and find one user that match
//POST /api/users/login
async function getUserLogin({user_name, password}) {
const user = await users.findOne({
$or: [{email: user_name}, {user_name: user_name}]
})
if (!user) {
throw Error("Invalid user")
}
if (!(typeof password === 'string' || password instanceof String)) {
throw Error("Invalid input for password")
}
const same = await bcrypt.compare(password, user.password)
if (!same) {
throw Error("Password doesn't match")
}
return user
}
//Get One
//GET /api/users/:userId
async function getUser({userId}) {
return await users.findOne({_id: ObjectID(userId)})
}
//Update One user, should be authorized
//Update base on userId
//PUT /api/users/:userId
async function updateUser({userId, updatedUser, userRole}) {
const user = await users.findOne({
$or: [{email: updatedUser.email}, {user_name: updatedUser.user_name}]
})
if (user) {
if (user._id != userId) {
throw Error("Username or email is already taken")
}
}
if (!updatedUser.email) {
throw Error("Requires an email")
}
if (typeof updatedUser.email === 'string' || updatedUser.email instanceof String) {
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
if(!(re.test(updatedUser.email.toLowerCase()))) {
throw Error("Incorrectly formatted email")
}
} else {
throw Error("Invalid input for email")
}
if (!updatedUser.user_name) {
throw Error("Requires an user name")
}
if (updatedUser.user_name) {
if (!(typeof updatedUser.user_name === 'string' || updatedUser.user_name instanceof String)) {
throw Error("Invalid input for user_name")
}
}
if (updatedUser.password !== null) {
if (!(typeof updatedUser.password === 'string' || updatedUser.password instanceof String)) {
throw Error("Invalid input for password")
}
}
//Hash password
const encrypted = await bcrypt.hash(updatedUser.password, 12)
updatedUser.password = encrypted
if (updatedUser.role) {
if (userRole !== "Admin") {
throw Error("No permission to update role")
}
if (typeof updatedUser.role === 'string' || updatedUser.role instanceof String) {
if (!(updatedUser.role === 'Manager' || updatedUser.role === 'Admin')) {
throw Error("Invalid role, role must be Manager or Admin")
}
} else {
throw Error("Invalid input for role")
}
}
const result = await users.findOneAndUpdate(
{_id: ObjectID(userId)},
{$set: {...updatedUser}}
)
return result
}
//Delete One user, should be authorized
//Delete user base on userId
//DELETE /api/users/:userId
async function deleteUser({userId}) {
const result = await users.findOneAndDelete({
_id: ObjectID(userId)
})
return result
}
//Reset password
//POST /api/users/resetPassword
async function resetPassword({email}) {
if (!email) {
throw Error("Missing email")
}
const user = await users.findOne({email: email})
if (!user) {
throw Error("No user with that email")
}
//Random 8 character string that can be any of the characters here: 0-9, a-z
var recoveryPassword = Math.random().toString(36).slice(-8)
//Hash password
const encrypted = await bcrypt.hash(recoveryPassword, 12)
const result = await users.findOneAndUpdate(
{email: email},
{$set: {password: encrypted}}
)
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.SENDER_EMAIL,
pass: process.env.SENDER_PASSWORD
}
})
const mailOptions = {
from: process.env.SENDER_EMAIL,
to: email,
subject: 'Password reset',
text: `Dear ${user.user_name},\nYou have made a password recover/reset request to indigenous plant.\nYour recovery password is: ${recoveryPassword}`
}
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
throw Error(error)
} else {
return (`Email send: ${info.response}`)
}
})
}
//Images
//Get All
//GET /api/images
async function getImages() {
return await images.find().toArray()
}
//Create
//Post /api/images
async function createImage({url, newImage}) {
if (!url) {
throw Error("Missing image")
}
const image = await images.findOne({
caption: newImage.caption
})
if (image) {
throw Error("Image caption is already taken")
}
if (!newImage.caption) {
throw Error("Missing caption")
}
if (!(typeof newImage.caption === 'string' || newImage.caption instanceof String)) {
throw Error("Invalid input for caption")
}
const result = await images.insertOne({
image_url: url,
...newImage
})
return result
}
//Get One
//GET /api/images/:imageId
async function getImage({imageId}) {
return await images.findOne({_id: ObjectID(imageId)})
}
//Update
//PUT /api/images/:imageId
async function updateImage({imageId, url, updatedImage, s3}) {
const image = await images.findOne({
caption: updatedImage.caption
})
if (image) {
if (image._id != imageId) {
throw Error("Image caption is already taken")
}
}
if (!updatedImage.caption) {
throw Error("Missing caption")
}
if (!(typeof updatedImage.caption === 'string' || updatedImage.caption instanceof String)) {
throw Error("Invalid input for caption")
}
//There is a new url, delete the old one from s3
if (url) {
const image = await images.findOne({_id: ObjectID(imageId)})
if (image.image_url) {
s3.deleteObject({
Bucket: process.env.AWS_BUCKET_NAME,
Key: image.image_url.split(".com/")[1]
}, function(err, data) {
if (err) {
console.log(err)
} else {
console.log("Success")
}
})
}
await images.findOneAndUpdate(
{_id: ObjectID(imageId)},
{$set: {
image_url: url
}}
)
}
const result = await images.findOneAndUpdate(
{_id: ObjectID(imageId)},
{$set: {
...updatedImage
}}
)
return result
}
//Delete
//DELETE /api/images/:imageId
async function deleteImage({imageId, s3}) {
//Delete the image from s3 if there is any
const image = await images.findOne({_id: ObjectID(imageId)})
if (image.image_url) {
s3.deleteObject({
Bucket: process.env.AWS_BUCKET_NAME,
Key: image.image_url.split(".com/")[1]
}, function(err, data) {
if (err) {
console.log(err)
} else {
console.log("Success")
}
})
}
const result = await images.findOneAndDelete({
_id: ObjectID(imageId)
})
return result
}
//Audios
//Get All
//GET /api/audios
async function getAudios() {
return await audios.find().toArray()
}
//Create
//Post /api/audios
async function createAudio({url, newAudio}) {
if (!url) {
throw Error("Missing audio")
}
const audio = await audios.findOne({
caption: newAudio.caption
})
if (audio) {
throw Error("Audio caption is already taken")
}
if (!newAudio.caption) {
throw Error("Missing caption")
}
if (!(typeof newAudio.caption === 'string' || newAudio.caption instanceof String)) {
throw Error("Invalid input for caption")
}
const result = await audios.insertOne({
audio_file_url: url,
...newAudio
})
return result
}
//Get One
//GET /api/audios/:audioId
async function getAudio({audioId}) {
return await audios.findOne({_id: ObjectID(audioId)})
}
//Update
//PUT /api/audios/:audioId
async function updateAudio({audioId, url, updatedAudio, s3}) {
const audio = await audios.findOne({
caption: updatedAudio.caption
})
if (audio) {
if (audio._id != audioId) {
throw Error("Audio caption is already taken")
}
}
if (!updatedAudio.caption) {
throw Error("Missing caption")
}
if (!(typeof updatedAudio.caption === 'string' || updatedAudio.caption instanceof String)) {
throw Error("Invalid input for caption")
}
//There is a new url, delete the old one from s3
if (url) {
const audio = await audios.findOne({_id: ObjectID(audioId)})
if (audio.audio_file_url) {
s3.deleteObject({
Bucket: process.env.AWS_BUCKET_NAME,
Key: audio.audio_file_url.split(".com/")[1]
}, function(err, data) {
if (err) {
console.log(err)
} else {
console.log("Success")
}
})
}
await audios.findOneAndUpdate(
{_id: ObjectID(audioId)},
{$set: {
audio_file_url: url
}}
)
}
const result = await audios.findOneAndUpdate(
{_id: ObjectID(audioId)},
{$set: {
...updatedAudio
}}
)
return result
}
//Delete
//DELETE /api/audios/:audioId
async function deleteAudio({audioId, s3}) {
//Delete file from s3
const audio = await audios.findOne({_id: ObjectID(audioId)})
if (audio.audio_file_url) {
s3.deleteObject({
Bucket: process.env.AWS_BUCKET_NAME,
Key: audio.audio_file_url.split(".com/")[1]
}, function(err, data) {
if (err) {
console.log(err)
} else {
console.log("Success")
}
})
}
const result = await audios.findOneAndDelete({
_id: ObjectID(audioId)
})
return result
}
//Videos
//Get All
//GET /api/videos
async function getVideos() {
return await videos.find().toArray()
}
//Create
//Post /api/videos
async function createVideo({newVideo}) {
if (!newVideo.video_url) {
throw Error("Missing video")
}
if (typeof newVideo.video_url === 'string' || newVideo.video_url instanceof String) {
const re = /^(https?\:\/\/)?(www\.youtube\.com|youtu\.?be)\/.+$/
if(!(re.test(newVideo.video_url.toLowerCase()))) {
throw Error("Incorrectly formatted video url")
}
} else {
throw Error("Invalid input for video_url")
}
const video = await videos.findOne({
caption: newVideo.caption
})
if (video) {
throw Error("Video caption is already taken")
}
if (!newVideo.caption) {
throw Error("Missing caption")
}
if (!(typeof newVideo.caption === 'string' || newVideo.caption instanceof String)) {
throw Error("Invalid input for caption")
}
const result = await videos.insertOne({
...newVideo
})
return result
}
//Get One
//GET /api/videos/:videoId
async function getVideo({videoId}) {
return await videos.findOne({_id: ObjectID(videoId)})
}
//Update
//PUT /api/videos/:videoId
async function updateVideo({videoId, updatedVideo}) {
if (!updatedVideo.video_url) {
throw Error("Missing video")
}
if (typeof updatedVideo.video_url === 'string' || updatedVideo.video_url instanceof String) {
const re = /^(https?\:\/\/)?(www\.youtube\.com|youtu\.?be)\/.+$/
if(!(re.test(updatedVideo.video_url.toLowerCase()))) {
throw Error("Incorrectly formatted video url")
}
} else {
throw Error("Invalid input for video_url")
}
const video = await videos.findOne({
caption: updatedVideo.caption
})
if (video) {
if (video._id != videoId) {
throw Error("Video caption is already taken")
}
}
if (!updatedVideo.caption) {
throw Error("Missing caption")
}
if (!(typeof updatedVideo.caption === 'string' || updatedVideo.caption instanceof String)) {
throw Error("Invalid input for caption")
}
const result = await videos.findOneAndUpdate(
{_id: ObjectID(videoId)},
{$set: {
...updatedVideo
}}
)
return result
}
//Delete
//DELETE /api/videos/:videoId
async function deleteVideo({videoId, s3}) {
//Delete file from s3
const video = await videos.findOne({_id: ObjectID(videoId)})
if (video.video_url) {
s3.deleteObject({
Bucket: process.env.AWS_BUCKET_NAME,
Key: video.video_url.split(".com/")[1]
}, function(err, data) {
if (err) {
console.log(err)
} else {
console.log("Success")
}
})
}
const result = await videos.findOneAndDelete({
_id: ObjectID(videoId)
})
return result
}
//Tags
//Get All
//GET /api/tags
async function getTags() {
return await tags.find().toArray()
}
//Create
//POST /api/tags
async function createTag({tag_name}) {
const tag = await tags.findOne({
tag_name: tag_name
})
if (tag) {
throw Error("Tag already exist")
}
if (!tag_name) {
throw Error("Require a tag name")
}
if (!(typeof tag_name === 'string' || tag_name instanceof String)) {
throw Error("Invalid input for tag_name")
}
const result = await tags.insertOne({
tag_name
})
return result
}
//Get One
//Get /api/tags/:tagId
async function getTag({tagId}) {
return await tags.findOne({_id: ObjectID(tagId)})
}
//Update
//PUT /api/tags/:tagId
async function updateTag({tagId, updatedTag}) {
const tag = await tags.findOne({
tag_name: updatedTag.tag_name
})
if (tag) {
if (tag._id != tagId) {
throw Error("Tag already exist")
}
}
if (!updatedTag.tag_name) {
throw Error("Require a tag name")
}
if (!(typeof updatedTag.tag_name === 'string' || updatedTag.tag_name instanceof String)) {
throw Error("Invalid input for tag_name")
}
const result = await tags.findOneAndUpdate(
{_id: ObjectID(tagId)},
{$set: {...updatedTag}}
)
return result
}
//Delete
//DELETE /api/tags/:tagId
async function deleteTag({tagId}) {
const result = await tags.findOneAndDelete({
_id: ObjectID(tagId)
})
return result
}
//Categories
//Get All
//GET /api/categories
async function getCategories() {
return await categories.find().toArray()
}
//Create
//POST /api/categories
async function createCategory({category_name, resource}) {
const category = await categories.findOne({
$and: [{category_name: category_name}, {resource: resource}]
})
if (category) {
throw Error("Category already exist in this resource group")
}
if (!category_name) {
throw Error("Require a category name")
}
if (!(typeof category_name === 'string' || category_name instanceof String)) {
throw Error("Invalid input for category_name")
}
if (!resource) {
throw Error("Require a resource")
}
if (typeof resource === 'string' || resource instanceof String) {
if (!(resource === 'plant' || resource === 'waypoint' || resource === 'tour' || resource === 'learn_more')) {
throw Error("Invalid resource, resource must be plant, waypoint, tour, or learn_more")
}
} else {
throw Error("Invalid input for resource")
}
const result = await categories.insertOne({
category_name,
resource
})
return result
}
//Get One
//GET /api/categories/:categoryId
async function getCategory({categoryId}) {
return await categories.findOne({_id: ObjectID(categoryId)})
}
//Update
//PUT /api/categories/:categoryId
async function updateCategory({categoryId, updatedCategory}) {
const category = await categories.findOne({
$and: [{category_name: updatedCategory.category_name}, {resource: updatedCategory.resource}]
})
if (category) {
if (category._id != categoryId) {
throw Error("Category already exist in this resource group")
}
}
if (!updatedCategory.category_name) {
throw Error("Require a category name")
}
if (!(typeof updatedCategory.category_name === 'string' || updatedCategory.category_name instanceof String)) {
throw Error("Invalid input for category_name")
}
if (!updatedCategory.resource) {
throw Error("Require a resource")
}
if (typeof updatedCategory.resource === 'string' || updatedCategory.resource instanceof String) {
if (!(updatedCategory.resource === 'plant' || updatedCategory.resource === 'waypoint' || updatedCategory.resource === 'tour' || updatedCategory.resource === 'learn_more')) {
throw Error("Invalid resource, resource must be plant, waypoint, tour, or learn_more")
}
} else {
throw Error("Invalid input for resource")
}
const result = await categories.findOneAndUpdate(
{_id: ObjectID(categoryId)},
{$set: {...updatedCategory}}
)
return result
}
//Delete
//DELETE /api/categories/:categoryId
async function deleteCategory({categoryId}) {
const result = await categories.findOneAndDelete({
_id: ObjectID(categoryId)
})
return result
}
//Get base on resource
//GET /api/categories/group/:group
async function getCategoryGroup({group}) {
return await categories.find({resource: group}).toArray()
}
//Locations
//Get All
//GET /api/locations
async function getLocations() {
return await locations.find().toArray()
}
//Create
//POST /api/locations
async function createLocation({location_name, longitude, latitude, description=""}) {
if (!location_name) {
throw Error("Require a location name")
}
if (!(typeof location_name === 'string' || location_name instanceof String)) {
throw Error("Invalid input for location_name")
}
if (longitude == null) {
throw Error("Require a longitude")
}
if (!(typeof longitude === 'number' && !Number.isNaN(longitude))) {
throw Error("Invalid input for longitude")
}
if (latitude == null) {
throw Error("Require a latitude")
}
if (!(typeof latitude === 'number' && !Number.isNaN(latitude))) {
throw Error("Invalid input for latitude")
}
if (!(typeof description === 'string' || description instanceof String)) {
throw Error("Invalid input for description")
}
const result = await locations.insertOne({
location_name,
longitude,
latitude,
description
})
return result
}
//Get One
//GET /api/locations/:locationId
async function getLocation({locationId}) {
return await locations.findOne({_id: ObjectID(locationId)})
}
//Update
//PUT /api/locations/:locationId
async function updateLocation({locationId, updatedLocation}) {
if (!updatedLocation.location_name) {
throw Error("Require a location name")
}
if (!(typeof updatedLocation.location_name === 'string' || updatedLocation.location_name instanceof String)) {
throw Error("Invalid input for location_name")
}
if (updatedLocation.longitude == null) {
throw Error("Require a longitude")
}
if (!(typeof updatedLocation.longitude === 'number' && !Number.isNaN(updatedLocation.longitude))) {
throw Error("Invalid input for longitude")
}
if (updatedLocation.latitude == null) {
throw Error("Require a latitude")
}
if (updatedLocation.latitude) {
if (!(typeof updatedLocation.latitude === 'number' && !Number.isNaN(updatedLocation.latitude))) {
throw Error("Invalid input for latitude")
}
}
if (updatedLocation.description) {
if (!(typeof updatedLocation.description === 'string' || updatedLocation.description instanceof String)) {
throw Error("Invalid input for description")
}
}
const result = await locations.findOneAndUpdate(
{_id: ObjectID(locationId)},
{$set: {...updatedLocation}}
)
return result
}
//Delete
//DELETE /api/locations/:locationId
async function deleteLocation({locationId}) {
const result = await locations.findOneAndDelete({
_id: ObjectID(locationId)
})
return result
}
//Revisions
//Get All
//GET /api/revisions
async function getRevisions() {
return await revisions.find().toArray()
}
//Create
//POST /api/revisions
async function createRevision({user_id}) {
if (!user_id) {
throw Error("User id missing")
}
const result = await revisions.insertOne({
user: ObjectID(user_id),
date: Date.now()
})
return result
}
//Get One
//GET /api/revisions/:revisionId
async function getRevision({revisionId}) {
return await revisions.findOne({_id: ObjectID(revisionId)})
}
//Delete
//DELETE /api/revisions/:revisionId
async function deleteRevision({revisionId}) {
const result = await revisions.findOneAndDelete({
_id: ObjectID(revisionId)
})
return result
}
//Plant
//Get All
//GET /api/plants/all
async function getPlants() {
//Fields like images must be array of ObjectId
//Should convert all the ObjectId array to array of their respective item
const aggregateOptions = [
{
$lookup: {
from: 'images',
localField: 'images',
foreignField: '_id',
as: 'images'
}
},
{
$lookup: {
from: 'audios',
localField: 'audio_files',
foreignField: '_id',
as: 'audio_files'
}
},
{
$lookup: {
from: 'videos',
localField: 'videos',
foreignField: '_id',
as: 'videos'
}
},
{
$lookup: {
from: 'tags',
localField: 'tags',
foreignField: '_id',
as: 'tags'
}
},
{
$lookup: {
from: 'categories',
localField: 'categories',
foreignField: '_id',
as: 'categories'
}
},
{
$lookup: {
from: 'locations',
localField: 'locations',
foreignField: '_id',
as: 'locations'
}
},
{
$lookup: {
from: 'revisions',
localField: 'revision_history',
foreignField: '_id',
as: 'revision_history'
}