-
Notifications
You must be signed in to change notification settings - Fork 0
/
dal.js
74 lines (64 loc) · 1.8 KB
/
dal.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
const MongoClient = require('mongodb').MongoClient;
const bcrypt = require('bcrypt');
const url = 'mongodb://localhost:27017/myproject';
let db = null;
// connect to mongo
const dbPromise = MongoClient.connect(url, { useUnifiedTopology: true })
.then(client => {
console.log('Connected to MongoDB');
return client.db("myproject");
})
.catch(err => {
console.error('Error connecting to MongoDB:', err);
process.exit(1);
});
// create user account
function create(name, email, password) {
return dbPromise.then(db => {
const collection = db.collection("users");
const hashedPassword = bcrypt.hashSync(password, 10);
const doc = { name, email, password, balance: 0 };
return collection.insertOne(doc)
.then(result => {
console.log(result);
return result.ops?.[0];
})
.catch(error => {
console.error('Error inserting document:', error);
throw error;
});
});
}
// login user
function find(email) {
return dbPromise.then((db) => {
const collection = db.collection('users');
return collection.findOne({ email });
});
}
// find user account
function find(email) {
return dbPromise.then(db => {
const collection = db.collection("users");
return collection.find({ email }).toArray();
});
}
// update - deposit/withdraw amount
function update(email, amount) {
return dbPromise.then(db => {
const collection = db.collection("users");
return collection.findOneAndUpdate(
{ email },
{ $inc: { balance: amount } },
{ returnOriginal: false }
);
});
}
// all users
function all() {
return dbPromise.then(db => {
const collection = db.collection("users");
return collection.find({}).toArray();
});
}
module.exports = { create, find, update, all };