-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.js
111 lines (85 loc) · 2.4 KB
/
database.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
const userName = process.env.MONGO_DB_USERNAME;
const password = process.env.MONGO_DB_PASSWORD;
const databaseAndCollection = { db: "final_project", collection: "users" };
const { MongoClient, ServerApiVersion } = require("mongodb");
const uri = `mongodb+srv://${userName}:${password}@cluster0.6vm3z.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
});
async function connect() {
await client.connect();
}
async function login(email) {
let result = await findUser(email);
if (!result) {
result = await createUser(email);
}
return result
}
async function findUser(user) {
let filter = { email: user.email };
const result = await client
.db(databaseAndCollection.db)
.collection(databaseAndCollection.collection)
.findOne(filter);
return result;
}
async function createUser(user) {
let newUser = {
name: user.name,
email: user.email,
photos: []
}
await client
.db(databaseAndCollection.db)
.collection(databaseAndCollection.collection)
.insertOne(newUser);
return newUser;
}
async function loadPhotos(email){
let filter = { email: email };
const user = await client
.db(databaseAndCollection.db)
.collection(databaseAndCollection.collection)
.findOne(filter);
return user.photos;
}
async function insertApplication(appplication) {
if (!(await findApplication(appplication.email))) {
const result = await client
.db(databaseAndCollection.db)
.collection(databaseAndCollection.collection)
.insertOne(appplication);
}
}
async function findApplication(email) {
let filter = { email: email };
const result = await client
.db(databaseAndCollection.db)
.collection(databaseAndCollection.collection)
.findOne(filter);
return result;
}
async function findByGPA(gpa) {
let filter = { gpa: { $gte: gpa } };
const cursor = await client
.db(databaseAndCollection.db)
.collection(databaseAndCollection.collection)
.find(filter);
const result = await cursor.toArray();
return result;
}
async function clear() {
const result = await client
.db(databaseAndCollection.db)
.collection(databaseAndCollection.collection)
.deleteMany({});
return result.deletedCount;
}
module.exports = {
connect,
login,
loadPhotos
};