-
Notifications
You must be signed in to change notification settings - Fork 0
/
db (copy).js
133 lines (116 loc) · 2.82 KB
/
db (copy).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
var MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
// , format = require('util').format;
var mongo = require('mongodb');
var serverOptions = {'auto_reconnect':true,'poolSize':10};
var client = new MongoClient(new Server('localhost',27017, serverOptions), {});
function addAUser(name,password, res)
{
client.open(function(err,client) //open database
{
var db = client.db('Tasks');
db.collection('tasks').find({username:name}).toArray(function(err,docs){
if(docs.length <= 0)
{
db.collection('tasks').insert({username:name,pass:password,salt:'SALT',tasks:[]},{w:1}, function(err,doc){
db.close();
if(err)
{
console.log("There was an error " + err);
res.json({message:'failed'});
}
else
{
res.json({message:'success'});
}
});
}
else //user already there. send error message
{
res.json({message:'duplicate'});
db.close();
}
});
});
}
function updateList(name,password,lists,res)
{
client.open(function (err,client){
var db = client.db('Tasks');
db.collection('tasks').find({username:name}).toArray(function(err,docs){
if(docs.length <= 0)
{
db.close();
res.json({message:'false:no user'});
}
else
{
if(docs[0].pass === password) //validate user
{
//add new tasks
db.collection('tasks').update({username:name},{$addToSet:{tasks:{$each:lists.add}}},function(err,docs){
console.log("update done ");
if(!err)
{
//delete exsiting tasks
//console.log(lists.delete);
db.collection('tasks').update({username:name},{$pullAll:{tasks:lists.delete}},function(err,doc){
if(!err)
{
//close transaction as true
res.json({message:'success'});
}
else
{
console.log('Error on delete: ' + err);
//close trasaction as false
res.json({message:'failed db update'});
}
db.close();
});
}
else
{
console.log('Error on add: ' + err);
//close transaction false
db.close();
res.json({message:'failed db update'});
}
});
}
else
{
db.close();
res.json({message:'false:bad password'});
}
}
});
});
}
function login(name,password,res)
{
client.open(function (err,client){
var db = client.db('Tasks');
db.collection('tasks').find({username:name}).toArray(function(err,docs){
db.close();
if(docs.length <= 0)
{
res.json({message:'false'});
}
else
{
if(docs[0].pass === password)
{
res.json({message:'true'});
}
else
{
res.json({message:'false'});
}
}
});
});
}
exports.addAUser = addAUser;
exports.login = login;
exports.updateList = updateList;