-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMongoUtils.js
More file actions
86 lines (74 loc) · 2.55 KB
/
Copy pathMongoUtils.js
File metadata and controls
86 lines (74 loc) · 2.55 KB
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
const MongoClient = require("mongodb").MongoClient;
//Connect to mongo
function MongoUtils() {
const mu = {};
//No es recomendable mostrar ninguna credencial al repositorio. Tengo entendido que el uso de dotenv es preferiblemente para uso de desarrollo.
//En el caso de Heroku todas estas variables se pueden agregar al ambiente del servidor (en el app.json)
let hostname = "localhost",
port = 27017,
dbName = "heroku_3lrh51h6",
colName = "some-mongo";
const user = process.env.MONGO_USER,
pwd = process.env.MONGO_PWD;
//Getters and Setters
mu.dbName = _dbName =>
_dbName !== undefined ? ((dbName = _dbName), mu) : dbName;
mu.hostname = _hostName =>
_hostName !== undefined ? ((hostname = _hostName), mu) : hostname;
mu.port = _port => (_port !== undefined ? ((port = _port), mu) : port);
//Acá dejaron imprimiendo en consola las credenciales.
mu.connect = () => {
console.log("Trying to connect");
let url;
if (user === undefined) {
url = process.env.MONGODB_URI;
} else {
url = `mongodb://${user}:${pwd}@${hostname}:${port}`;
}
console.log(url);
const cliente = new MongoClient(url);
console.log("Connected");
return cliente.connect();
};
mu.getTest = client => {
const colTest = client.db(dbName).collection("test");
console.log("getTest");
return colTest
.find({})
.limit(10)
.toArray()
.finally(() => client.close());
};
mu.users = {};
mu.users.findUser = userName =>
mu.connect().then(client => {
const usersC = client.db(dbName).collection(colName);
// when searching by id we need to create an ObjectID
return usersC
.findOne({ userName: userName })
.finally(() => client.close());
});
mu.users.insertUser = user =>
mu.connect().then(client => {
const usersC = client.db(dbName).collection(colName);
return usersC.insertOne(user).finally(() => client.close());
});
//En este método se les olvidó cerrar el cliente. Esto puede crear mal uso de los recursos.
mu.users.find = client => {
const usersC = client.db(dbName).collection(colName);
return usersC
.find()
.sort({ score: -1 })
.toArray();
};
mu.users.updateScore = (userName, newScore) =>
mu.connect().then(client => {
const usersC = client.db(dbName).collection(colName);
return usersC
.updateOne({ userName: userName }, { $set: { score: newScore } })
.finally(() => client.close());
});
return mu;
}
const mu = MongoUtils();
module.exports = MongoUtils;