-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
70 lines (57 loc) · 1.85 KB
/
db.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
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://' + process.env.MONGO_CONNECTION;
const dbName = process.env.MONGO_DB;
const dbParams = { useNewUrlParser: true, useUnifiedTopology: true };
MongoClient.connect(url, dbParams, (err, conn) => {
if (err) return console.log('error', err);
// Storing a reference to the database so you can use it later
global.conn = conn.db(dbName);
console.log(`Connected MongoDB: ${url}`);
console.log(`Database: ${dbName}`);
})
const TAMANHO_PAGINA = 10;
var ObjectId = require("mongodb").ObjectId;
function findAll(pagina, callback) {
const tamanhoSkip = TAMANHO_PAGINA * (pagina - 1);
global.conn.collection("users").find({})
.skip(tamanhoSkip)
.limit(TAMANHO_PAGINA)
.toArray(callback);
}
//callback deve considerar error e count
function countAll(callback) {
global.conn.collection("users").count(callback);
}
function insert(user, callback) {
global.conn.collection("users").insert(user, callback);
}
function findOne(id, callback) {
global.conn.collection("users").find(new ObjectId(id)).toArray(callback);
}
function findUserByName(username, callback){
global.conn.collection("users").findOne({"username": username}, function(err, doc){
callback(err, doc);
});
}
function findUserById(id, callback){
global.conn.collection("users").findOne({_id: ObjectId(id) }, (err, doc) => {
callback(err, doc);
});
}
function update(id, user, callback) {
global.conn.collection("users").updateOne({ _id: new ObjectId(id) }, { $set: user }, callback);
}
function deleteOne(id, callback) {
global.conn.collection("users").deleteOne({ _id: new ObjectId(id) }, callback);
}
module.exports = {
findAll,
insert,
findOne,
findUserByName,
findUserById,
update,
deleteOne,
countAll,
TAMANHO_PAGINA
}