-
Notifications
You must be signed in to change notification settings - Fork 2
/
database.js
67 lines (50 loc) · 1.61 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
64
65
66
67
//Connecting to the database
let mongoose = require('mongoose');
let db = mongoose.connection;
const User = require('./models/User');
const Thread = require('./models/Thread');
const Message = require('./models/Message');
const fs = require('fs');
mongoose.Promise = global.Promise;
let addUser = function(user){
let tempUser = new User(user);
tempUser.save();
return tempUser._id;
}
let addThread = function(thread){
let tempThread = new Thread(thread);
tempThread.save();
return tempThread._id;
}
let addMessage = function(message){
let tempMessage = new Message(message);
tempMessage.save();
return tempMessage._id;
}
let deleteMessage = async function(messageId){
let message = await db.collections.messages.findOne({_id: mongoose.Types.ObjectId(messageId)});
let files = message.files;
for(let i = 0; i < files.length; i++){
fs.unlink('uploads/' + files[i], (err) => {});
}
db.collections.messages.findOneAndDelete({_id: mongoose.Types.ObjectId(messageId)});
}
let deleteThread = async function(threadId){
let thread = await db.collections.threads.findOne({_id: mongoose.Types.ObjectId(threadId)});
for(let i = 0; i < thread.messageID_list.length; i++){
deleteMessage(thread.messageID_list[i]);
}
db.collections.threads.deleteOne({_id: mongoose.Types.ObjectId(threadId)});
}
let deleteUser = async function(userId){
db.collections.users.deleteOne({_id: mongoose.Types.ObjectId(userId)});
}
let functions = {
addUser,
addThread,
addMessage,
deleteMessage,
deleteThread,
deleteUser
};
module.exports = functions;