-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdatabase.js
63 lines (57 loc) · 1.48 KB
/
database.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
/* montreus-chat
* server/database.js
* MongoDB communicator for Montreus Chat.
*/
//NPM Modules
var mongoose = require("mongoose");
//Globals
var config = require("./config");
var Schema = mongoose.Schema;
//Startup Routines
mongoose.connect(config.database.address, {server: { poolSize: 5, keepAlive: 1 } },function (error) {
if (error) {
console.warn(error);
}else{
console.log("Connection to MongoDB established");
}
});
//MongoDB Globals
var MessageSchema = new Schema({
result: {},
room: String,
sent: Date
});
var Message = mongoose.model('Message', MessageSchema);
//
var findMessages = function(room) {
return new Promise(function (resolve, decline){
Message.find({room: room}).sort({sent: 'ascending'}).exec(function(error, messages) {
if(!error){
resolve(messages);
}else{
console.error(error.message);
decline(error);
}
});
});
}
var addNewMessage = function(result, room){
return new Promise(function (resolve, decline){
var newMessage = new Message({
result: result,
room: room,
sent: new Date()
});
newMessage.save(function(error){
if(!error){
resolve();
}else{
console.error(error);
decline(error);
}
});
});
}
//Exporting methods
exports.find = findMessages;
exports.add = addNewMessage;