forked from node-organic/organic-mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
71 lines (61 loc) · 1.83 KB
/
index.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
var mongoose = require("mongoose")
module.exports = function OrganicMongoose(plasma, config){
this.config = config
this.config.emitReady = config.emitReady || "Mongoose"
this.config.database.host = this.config.database.host || "localhost"
this.config.database.port = this.config.database.port || 27017
this.config.database.options = this.config.database.options || {}
this.emit = function(type) {
plasma.emit(type)
}
if(config.reactOn)
plasma.on(config.reactOn, this.connect, this)
else
this.connect(null)
plasma.on("kill", this.disconnect, this)
}
module.exports.prototype.connect = function(c, next){
var self = this
if (global.Promise) {
mongoose.Promise = global.Promise
}
else {
mongoose.Promise = require("bluebird")
}
mongoose.connect(self.config.database.host,
self.config.database.name,
self.config.database.port,
self.config.database.options,
function(err){
if (err) {
console.error(err)
return next && next(err)
}
if(self.config.recreateDatabase) {
mongoose.connection.db.dropDatabase(function(){
// workaround mongoose.connection issue with dropped db and open connection
mongoose.connection.db.close(function(){
mongoose.connection.readyState = 0
mongoose.connect(self.config.database.host,
self.config.database.name,
self.config.database.port,
self.config.database.options,
function(err){
if(err) {
console.error(err)
return next && next(err)
}
self.emit(self.config.emitReady)
next && next()
})
})
})
} else {
self.emit(self.config.emitReady)
next && next()
}
})
}
module.exports.prototype.disconnect = function(c, next){
mongoose.disconnect(next)
}