-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdal.js
78 lines (67 loc) · 2.06 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
75
76
77
78
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
let db = null;
// connect to mongo
MongoClient.connect(url, { useUnifiedTopology: true }, function (err, client) {
console.log("Connected successfully to db server");
// connect to myproject database
db = client.db('myproject');
});
// create user account
function create(name, email, password) {
return new Promise((resolve, reject) => {
const collection = db.collection('users');
const doc = { name, email, password, balance: 0 };
collection.insertOne(doc, { w: 1 }, function (err, result) {
err ? reject(err) : resolve(doc);
});
})
}
// find user account
function find(email) {
return new Promise((resolve, reject) => {
const customers = db
.collection('users')
.find({ email: email })
.toArray(function (err, docs) {
err ? reject(err) : resolve(docs);
});
})
}
// find user account
function findOne(email) {
return new Promise((resolve, reject) => {
const customers = db
.collection('users')
.findOne({ email: email })
.then((doc) => resolve(doc))
.catch((err) => reject(err));
})
}
// update - deposit/withdraw amount
function update(email, amount) {
return new Promise((resolve, reject) => {
const customers = db
.collection('users')
.findOneAndUpdate(
{ email: email },
{ $inc: { balance: amount } },
{ returnOriginal: false },
function (err, documents) {
err ? reject(err) : resolve(documents);
}
);
});
}
// all users
function all() {
return new Promise((resolve, reject) => {
const customers = db
.collection('users')
.find({})
.toArray(function (err, docs) {
err ? reject(err) : resolve(docs);
});
})
}
module.exports = { create, findOne, find, update, all };