Page Menu
Home
Sealhub
Search
Configure Global Search
Log In
Files
F7859929
mongo_connections.js
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
1 KB
Referenced Files
None
Subscribers
None
mongo_connections.js
View Options
//przekopiowane ze stackoverflow
var
mongo
=
require
(
'mongodb'
);
// a mongo connection cache
// pass in host & port
// it returns a function accepting dbName, collectionName & callback
var
mongoCache
=
function
(
host
,
port
){
// keep our open connections
var
mongoDatabases
=
{};
var
ensureDatabase
=
function
(
dbName
,
readyCallback
){
// check if we already have this db connection open
if
(
mongoDatabases
[
dbName
]){
readyCallback
(
null
,
mongoDatabases
[
dbName
]);
return
;
}
// get the connection
var
server
=
new
mongo
.
Server
(
host
,
port
/*, {auto_reconnect: true, w:1, journal:true, safe: true}*/
);
// get a handle on the database
var
db
=
new
mongo
.
Db
(
dbName
,
server
,
{
w
:
1
});
db
.
open
(
function
(
error
,
databaseConnection
){
if
(
error
)
throw
error
;
// add the database to the cache
mongoDatabases
[
dbName
]
=
databaseConnection
;
// remove the database from the cache if it closes
databaseConnection
.
on
(
'close'
,
function
(){
delete
(
mongoDatabases
[
dbName
]);
})
// return the database connection
readyCallback
(
error
,
databaseConnection
);
})
}
var
ensureCollection
=
function
(
dbName
,
collectionName
,
readyCallback
){
ensureDatabase
(
dbName
,
function
(
error
,
databaseConnection
){
if
(
error
)
throw
error
;
databaseConnection
.
createCollection
(
collectionName
,
function
(
error
,
collection
)
{
if
(
error
)
throw
error
;
// return the collection finally
readyCallback
(
error
,
collection
);
})
})
}
return
ensureCollection
;
}
module
.
exports
=
mongoCache
;
File Metadata
Details
Attached
Mime Type
text/plain
Expires
Wed, Aug 13, 17:10 (1 d, 5 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
868428
Default Alt Text
mongo_connections.js (1 KB)
Attached To
Mode
rS Sealious
Attached
Detach File
Event Timeline
Log In to Comment