/
mongoose.js
74 lines (67 loc) 路 1.84 KB
/
mongoose.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
const mongod = require('mongod');
const mongoose = require('mongoose');
const path = require('path');
const port = process.env.DB_PORT;
const url = `mongodb://localhost:${port}/`;
const dbpath = process.env.DB_PATH;
mongoose.Promise = global.Promise;
const mongoDB = new mongod({
port: port,
dbpath: path.join(__dirname, '.', dbpath)
});
const followerSchema = new mongoose.Schema({
login: String
});
const FollowerToProcess = mongoose.model("FollowerToProcess", followerSchema);
const ProcessedFollower = mongoose.model("ProcessedFollower", followerSchema);
const Temporary = mongoose.model("Temporary", followerSchema);
const schemas = {
FollowerToProcess : FollowerToProcess,
ProcessedFollower : ProcessedFollower,
Temporary : Temporary
};
const initialize = () => {
return mongoDB.open()
.then(() => {
console.log('MongoDB: Opened.');
})
};
const terminate = () => {
return mongoDB.close()
.then(()=>{
console.log('MongoDB: Closed.');
})
};
const connect = (database) => {
return mongoose.connect(url + database, {
useMongoClient: true,
// I don't know what to do about the connection timeout issue:
// https://stackoverflow.com/questions/40585705/connection-timeout-for-mongodb-using-mongoose
// http://mongoosejs.com/docs/connections.html#options
socketTimeoutMS: 0,
keepAlive: true,
reconnectTries: 30
/* other options */
}, ()=>{
console.log('Mongoose: Connected.');
});
};
const disconnect = () => {
return mongoose.disconnect(()=>{console.log('Mongoose: Disconnected.')});
};
const save = (Model, dataArray) => {
return new Promise((resolve, reject)=>{
Model.create(dataArray, function (err, results) {
if (err) return reject(err);
return resolve(dataArray);
})
});
};
module.exports = {
connect,
disconnect,
initialize,
terminate,
save,
schemas
};