jdesboeufs / connect-mongo Goto Github PK
View Code? Open in Web Editor NEWMongoDB session store for Express
License: MIT License
MongoDB session store for Express
License: MIT License
I noticed that even on my localhost simple HTTP requests started taking about 2 seconds after using connect-mongo.
I wrote a simple hook for Express to figure out how much time each middleware is occupying:
//create a new HTTP server
var server = express();
require('./profiler')(server, 10);
module.exports = function(server, limit) {
var _use = server.use,
mwi = 0;
server.use = function(fn) {
var _fn = fn;
fn = function(req, res, next) {
console.time("middleware" + (++mwi));
var _next = next,
time = process.hrtime();
(function(i, time, url) {
next = function() {
console.timeEnd("middleware" + i)
var diff = process.hrtime(time),
nano = diff[0] * 1e9 + diff[1],
ms = nano * 1e-6;
if (ms > limit) {
console.info("%s: middleware %d took %d milliseconds", url, i, ms);
console.trace("middleware" + i);
}
_next.apply(this, Array.prototype.slice.call(arguments));
};
})(mwi, time, req.url);
_fn.apply(this, Array.prototype.slice.call(arguments));
};
_use.apply(this, Array.prototype.slice.call(arguments));
};
};
This is the result: https://gist.github.com/anonymous/deea64449e5390f4cfe6
As you can see, there are two points of interest:
The second point is simple. I can write my own middleware to only enable sessions for specific requests. However, for these requests, how can I make it faster than 250-500ms? In other words is there any way to improve connect-mongo's performance?
It is worth noting that I am using MongoLab.com, and therefore my db server is a remote one.
I get the above mentioned error as soon as more than 1 user tries to login into my system.
I am using MongoStore like this
app.use(express.session({
key: 'sid',
secret: 'secret',
store: new MongoStore({
db: 'sessions',
secret: 'mongo store secret!'
})
});
Sorry, wrong problem didn't read that I need to pass express to require('connect-mongo')
I did work around this issue, but it is pretty ugly and should be resolved in the code.
This is my config object:
session_store_config = {
"url": "mongodb://{host}:27017/session/session",
"collection": "session",
"username": "{username}",
"password": "{password}",
"auto_reconnect": true,
"mongoose_connection": {
"db": {
"databaseName": "session",
"serverConfig": {
"host": "{host}",
"port": 27017,
"options": {"auto_reconnect": true, "poolSize": 5, "socketOptions": { "keepAlive": 60 }}
}
}
}
}
var session_store = new MongoStore(session_store_config);
Basically the workaround is to provide the "mongoose_connection" object (even though I'm not using mongoose) as this is currently the only way to expose the serverConfig.options.socketOptions so that keepAlive can be provided to prevent connection timeouts from idle time. The socketOptions is part of the MongoDB api, and should be exposed directly so we don't have to use this hack.
Please see http://stackoverflow.com/questions/18679485/why-does-a-session-parameter-with-type-objectid-mongodb-transform-to-a-string for a detailed description.
When MongoDB goes down, I wouldn't expect connect-mongo to just crash. I get the following error response on the webpage:
Error: notConnected
at [object Object].executeCommand (/Users/me/myapp/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:779:25)
at Collection.findOne (/Users/me/myapp/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/collection.js:773:11)
at /Users/me/myapp/node_modules/connect-mongo/lib/connect-mongo.js:143:16
at MongoStore._get_collection (/Users/me/myapp/node_modules/connect-mongo/lib/connect-mongo.js:92:19)
at MongoStore.get (/Users/me/myapp/node_modules/connect-mongo/lib/connect-mongo.js:142:8)
at Object.session [as handle] (/Users/me/myapp/node_modules/express/node_modules/connect/lib/middleware/session.js:319:11)
at next (/Users/me/myapp/node_modules/express/node_modules/connect/lib/http.js:201:15)
at /Users/me/myapp/node_modules/express/node_modules/connect/lib/middleware/static.js:148:11
Can we handle this better so my app can at least do something when session support isn't available?
connect-gzip is not working with npm install in Node.0.4.12
It said "UNMET DEPENDENCY"
said it is not compatible with my version of node/npm but I'm using the Node.0.4.12 npm 1.0.93
I don't want to run this on Unstable Node 0.5 version. anyway I can make it run on 0.4.12?
crypto.js:129
return (new Hmac).init(hmac, key);
^
TypeError: Not a string or buffer
at Object.createHmac (crypto.js:129:21)
at Object.sign (/project/node_modules/connect-mongo/node_modules/connect/lib/utils.js:135:6)/project/node_modules/connect-mongo/node_modules/connect/lib/middleware/session/cookie.js:115:17)
at Object.serialize (
at ServerResponse.writeHead (~/project/node_modules/express/node_modules/connect/lib/middleware/session.js:265:46)
at ServerResponse._implicitHeader (http.js:796:8)
at ServerResponse.end (http.js:653:10)
at ~/project/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js:73:19
at [object Object]. (fs.js:115:5)
at [object Object].emit (events.js:64:17)
at afterRead (fs.js:1111:12)
Dependency in package.json should be:
"connect": ">=1.0.3 <2",
instead of
"connect": ">=1.0.3",
Cheers,
Philipp
Hi,
I'm using connect-mongo and until now it was working great!
Today I've tried to use formaline to manage file uploads in my application but it didn't work.
From what I gathered there seems to be some issue between formaline and connect-mongo.
Can you please see the issue coolaj86/formaline#25 and see if you can help?
Thanks.
Best regards,
Hugo
Something in commit 8c07c3b changes the mongo access behavior enough that Mongo now throws the error:
RangeError: Maximum call stack size exceeded
whenever sessions are accessed at least in my use case (I have a hunch it relates mongo connection setup using an instantiated DB object rather than connection host/port and credentials). I'm still investigating the issue and will post a minimal example and test case when I have one assembled. It appears also that this checkin broke the test case that would have caught the flaw. It seems others have encountered this issue http://stackoverflow.com/questions/16013436 although I'm not using mongoose, nor express. My stack is Node v0.10.20, Connect 2.11.0, Mongodb 1.3.19
I'll update further when I have a test case and/or solution
Update: As the stackoverflow question is about the same error being generated, the cause must be different as that question was posted long before this checkin which seems to have yielded the problems in my case.
After I did an upgrade on node and npm (connect-mongo @ 0.1.7),
when I do the
express.createServer(
express.cookieParser(),
express.bodyParser(),
express.session({ secret: cfg.session_secret,
cookie: { domain: 'mydomain.com' },
store:new MongoStore({
db: cfg.db_session_name,
host: cfg.db_ip,
port: cfg.db_port
}
)
})
)
Then, once i hit any url / route, I will run into infinite loop:
TypeError: Not a string or buffer
at Object.createHmac (crypto.js:129:21)
at Object.sign (/node_modules/connect-mongo/node_modules/connect/lib/utils.js:135:6)
at Object.serialize (/node_modules/connect-mongo/node_modules/connect/lib/middleware/session/cookie.js:115:17)
at ServerResponse.writeHead (/node_modules/express/node_modules/connect/lib/middleware/session.js:265:46)
at ServerResponse._implicitHeader (http.js:808:8)
at ServerResponse.end (http.js:645:10)
at next (/node_modules/express/node_modules/connect/lib/http.js:167:13)
at pass (/node_modules/express/lib/router/index.js:219:24)
at nextRoute (/node_modules/express/lib/router/index.js:209:7)
at callbacks (/node_modules/express/lib/router/index.js:274:11)
The script was fine an hour ago, but then it just blow up if I use the MOngoStore for express session. is there something wrong I did?
Doing some benchmarking of thousands of requests a second, there have been plenty of sessions created in mongodb that look like:
"{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},\"passport\":{}}"
However, connect-mongo doesn't seem to have any capabilities for removing these sessions. Setting clear_interval
only wipes things which has a maxAge set not things that don't.
Any thoughts?
in case, when session storage can be used by satelite code such as socket.io asincronous listeners, we need save some unknown data, wich may be stored by some callbacks
for example:
vhost.soc.on('init', function(key){
var sid = vhost.soc.handshake.sid ? vhost.soc.handshake.sid : false;
if(!sid){
console.dir('sid fail')
vhost.soc.emit('init', {loggedin:false})
} else {
vhost.sessions.findOne({_id:sid},function(err,ses){
if(ses.siodata){
vhost.soc.emit('init', ses.siodata)
if(ses.siodata.loggedin){
console.dir(['logged in', ses])
vhost.soc.emit('login', login({login:ses.siodata.login}))
}
} else {
console.dir(['login fail', ses])
vhost.soc.emit('init', {loggedin:false})
}
})
}
});
in this example socket.io callback store field "siodata" in session document, which will be used in the future, after page refresh, but on app.get connect-mongo complete rewrite this session document and siodata will be lost
MongoStore.prototype.set = function(sid, session, callback) {
try {
//var s = {_id: sid, session: this._serialize_session(session)};
//so we will not hardcode session body
var i = this; // save this scope
this._get_collection(function(collection) {
// instead, we try to get session with _id = sid from collection
collection.findOne({_id: sid},function(err,ses){
// added one more opportunity for errors - processed
if(err) {
callback && callback(err);
} else {
// and carefully set s if document exists, or hardcode session object in other case
var s = ses || {_id: sid };
// renew session info in both cases
s.session = i._serialize_session(session);
if (session && session.cookie && session.cookie._expires) {
s.expires = new Date(session.cookie._expires);
}
// now we can update session document without destruct of posible additional session data
collection.update({_id: sid}, s, {upsert: true, safe: true}, function(err, data) {
if (err) {
callback && callback(err);
} else {
callback && callback(null);
}
});
}
});
});
} catch (err) {
callback && callback(err);
}
};
regards, all,
wait your comments about
When I set stringify: false
and run my server I get the following error as soon as a session is retrieved:
/project/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/server.js:529
throw err;
^
TypeError: Object #<Object> has no method 'serialize'
at ServerResponse.<anonymous> (/project/node_modules/express/node_modules/connect/lib/middleware/session.js:270:20)
at ServerResponse.EventEmitter.emit (events.js:117:20)
at ServerResponse.res.writeHead (/project/node_modules/express/node_modules/connect/lib/patch.js:73:36)
at ServerResponse._implicitHeader (http.js:1132:8)
at ServerResponse.OutgoingMessage.end (http.js:921:10)
at /project/node_modules/express/node_modules/connect/lib/middleware/session.js:285:13
at /project/node_modules/connect-mongo/lib/connect-mongo.js:245:25
at null.<anonymous> (/project/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/collection.js:480:9)
at g (events.js:175:14)
at EventEmitter.emit (events.js:106:17)
I'm using a Mongoose connection.
How can I connect through unix domain socket to mongodb ?
I have a crash issue:
/home/ubuntu/www/node_modules/mongodb/lib/mongodb/connection/server.js:353
throw err;
^
Error: Cannot write after end
at Gzip.write (zlib.js:316:31)
at ServerResponse.write (/home/ubuntu/www/node_modules/express/node_modules/connect/lib/middleware/compress.js:84:18)
at ServerResponse.end (/home/ubuntu/www/node_modules/express/node_modules/connect/lib/middleware/compress.js:89:23)
at /home/ubuntu/www/node_modules/express/node_modules/connect/lib/middleware/session.js:256:13
at /home/ubuntu/www/node_modules/connect-mongo/lib/connect-mongo.js:201:25
at [object Object].<anonymous> (/home/ubuntu/www/node_modules/mongodb/lib/mongodb/collection.js:424:9)
at [object Object].g (events.js:156:14)
at [object Object].emit (events.js:88:20)
at Db._callHandler (/home/ubuntu/www/node_modules/mongodb/lib/mongodb/db.js:1197:25)
at /home/ubuntu/www/node_modules/mongodb/lib/mongodb/connection/server.js:346:30
I am using express 3. But this issue can be fixed by putting a try catch around line 201 as indicated by the debug.
My issue is that sessions don't seem to be deleted from MongoDB when they expire, so the db size grows until the disk is full. I saw in another issue a comment indicating that connect-mongo asks MongoDB to remove expired sessions, so I'm not sure what may be happening in my case.
I'm currently running the following versions:
node 0.7.0-pre
connect-mongo 0.1.7
express 2.5.2
connect 1.8.5
Also, should I need to run db.repairDatabase() occasionally to reclaim disk space?
Thanks
I guess this is more of a feature request, to add "db Database name OR fully instantiated node-mongo-native object" from https://github.com/hillct/connect-mongo, in addition to "mongoose_connection".
I'm trying to access the session on another file outside of my server.js where I have:
app.use(express.session({
cookie: {maxAge: 86400000 * 7},
secret: 'secretkey',
store: new MongoStore(dbOptions)
}));
Here is what I tried to do:
var MongoStore = require('connect-mongo')
var pattern=/.*connect\.sid=([\w\d]+\.[\w\d]+)/gi;
var sid = client.request.headers.cookie.replace(pattern, '$1');
MongoStore.get(sid, function (session) {
console.log(session)
})
This does not work, i get MongoStore does not have the method .get. What's the correct way? Thanks.
When connect-mongo attempts to connect to a missing database, it will enter a very fast loop which spikes the CPU. The loop seems to occur when in the "waiting" state.
steps to reproduce:
(Tested in Ubuntu 10.04 LTS and 10.10 - npm package install [email protected] also tested 0.1.5)
Set up a node project with a valid connection string to a missing or disabled database:
add a log message in /opt/server/../node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection.js at the method:
var waitForConnections = function() {
// Emit a connect message once all connections are up
Observe that the CPU in top quickly reaches 100% usage and that it emits many waiting messages. It would seem that this loop is somewhere near the actual issue.
the tested connection string looks like this:
var sys = require('sys'),
MongoStore = require('connect-mongo'),
test = new MongoStore({ db: 'mydatabase', host: '10.20.101.160', port: 27017 });
Error messages received after loop completes in about 10-30 seconds:
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Error connecting to database
at /opt/server/../node_modules/connect-mongo/lib/connect-mongo.js:106:13
at /opt/server/../node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:79:30
at [object Object]. (/opt/server/../node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connections/server.js:121:12)
at [object Object].emit (events.js:64:17)
at Array. (/opt/server/../node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection.js:242:14)
at EventEmitter._tickCallback (node.js:126:26)
expected result:
The default settings for a connection should not allow CPU usage level should not rise in the event of a database outage. This is especially dangerous if Node.js is started in an upstart task with the ability to respawn on error.
I'm getting this error:
Error: Cannot write after end
at Gzip.write (zlib.js:282:31)
at ServerResponse.write (/home/ubuntu/www/node_modules/connect/lib/middleware/compress.js:84:18)
at ServerResponse.end (/home/ubuntu/www/node_modules/connect/lib/middleware/compress.js:89:23)
at /home/ubuntu/www/node_modules/connect/lib/middleware/session.js:256:13
at /home/ubuntu/www/node_modules/connect-mongo/lib/connect-mongo.js:201:25
at [object Object].<anonymous> (/home/ubuntu/www/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/collection.js:429:9)
at [object Object].g (events.js:156:14)
at [object Object].emit (events.js:88:20)
at Db._callHandler (/home/ubuntu/www/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:1292:25)
at /home/ubuntu/www/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/server.js:352:30
I'm using connect 2 and express 3 alpha.
I am using mongolab for hosting the sessions and the app is under the heroku host, some times the starting application gives the error.
**/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/server.js:529
throw err;
^
Error: Error setting TTL index on collection : sessions <MongoError: not authorized for query on herouku*****.system.indexes>
After going further it seems there is problem with executing the ensureIndex, does this get executed evert connect?
Or can this just be removed and be set from mongo shell ?
I suppose the fix is to just add another item in the files array for "lib", but I'm not sure.
Instead of creating a new Db object, can't you just reuse the db object already instantiated by mongoose?
I.e. at https://github.com/kcbanner/connect-mongo/blob/master/lib/connect-mongo.js#L79 you'd simply do:
if (options.mongoose.connection) {
this.db = options.mongoose.connection.db;
}
I didn't test this, but this seems to make more sense to me than to create a new instance with its own settings and failover mechanics.
I noticed that my sessions weren't expiring, so I checked the indexes on my collection, and there was only one set for _id
.
It seems that you're calling ensureIndex()
on the collection in line 135 of connect-mongo.js, but apparently it wasn't called on my end. To fix it I manually ran this:
db.sessions.ensureIndex({expires: 1}, {expireAfterSeconds: 0});
I'm using a mongoose_connection
rather than providing the connection info to connect-mongo, that makes any difference.
I looked into the mongoDB. The session is stored as string:
{
"_id": String,
"session": String
}
session is not stored as object. Why is that?
I was wondering if it's possible to attach a callback to be performed when a session is cleared? In my particular case, the session also stores the _id of a User model, and I'd like to delete the User with the session.
npm install reads:
package.json must be actual JSON, not just JavaScript
This is not a bug in npm.
Tell the packagge author to fix their package.json file. JSON.parse
Would be great if we could pass in auth options to the db.authenticate method (http://mongodb.github.io/node-mongodb-native/api-generated/db.html#authenticate) in addition to the username and password options here:
https://github.com/kcbanner/connect-mongo/blob/master/lib/connect-mongo.js#L174
That way we can authenticate against a different db than the one we're using.
I have switched my application to using mongodb 2.2.2 and 'connect-mongo' started failing @ connect time (getting a connection exception @ db.open.) To test, I have switch only the session storage to my old instance (2.2.1) and that fixed the problem…
I see that in the dependencies of connect-mongo it is using mongodb 1.0.x, the newer version are at 1.1.x… I suspect that this might be the problem, but I can't confirm yet.
Anyone has thoughts about this?
Currently, when the node app starts and I send it a request before connect-mongo could connect to the database, I get an error like:
TypeError: Cannot read property 'arbiterOnly' of undefined
at .../node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/server.js:558:22
at [object Object].checkoutReader (.../node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/server.js:575:16)
at .../node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:1344:79
at Db._executeQueryCommand (.../node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:1555:5)
at Cursor.nextObject (.../node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/cursor.js:455:13)
at Array.0 (/.../node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/cursor.js:162:12)
at EventEmitter._tickCallback (node.js:192:40)
But if there was an ASync method with a callback, I can start the server once connect-mongo is connected.
I have two nodejs servers (web-server, socket-server), that are connected to each other by socket.io. On web-service I use express.js and passport.js as authentication middleware.
This is my web-server config:
var express = require('express'),
mongo = require('mongodb'),
io = require('socket.io'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
MongoStore = require('connect-mongo')(express);
app.configure(function () {
app.use(express.cookieParser());
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(express.session({
secret: 'keyboard cat',
store: new MongoStore({
db: 'MyDatabase'
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(__dirname + '/htdocs'));
});
When I use connect-mongo, it creates a new session for each http-request:
(0 element creates with log in request, other elements are created, when I press F5).
When web-server takes socket connection, connect-mongo creates new session. There are about 50 new documents per minute.
What could be the reason?
In the case of updating the page, helped tip to add app.use(express.favicon()).
With sockets question is still actual.
My socket-server code
function sendPortalJSON (portal_id, data, _event) {
https.get({
host : ...,
port : ...,
path : "/" + _event + "?data=" + encodeURIComponent( JSON.stringify (data))
}).on('error', function (err) {
});
}
...
sendPortalJSON(1, agent_data[i].d, "cpu-details");
And on web-server:
app.get('/cpu-details', function (req, res) {});
_expires
is a property used by the setter/getter for the expires
property on the intended cookie object. See senchalabs/connect/middleware/session/cookie.js:40
Tests should not expect this property to be present, and it should not be stored in the database.
Pull #74 uses cookie.toJSON()
to get the correct cookie object, which does not contain the _expires
property, so the tests needed to be corrected to pass.
Hello, i'm using the connect-mongodb app on two differents Node.js applications.
First: http://myapp.com
Second: http://two.myapp.com
I want to access the first application session in the second one, and vice versa.
I've been trying to force the cookie domain to ".myapp.com" but when I did it, I wasn't able to log-in anymore (in any of the two applications).
When I test my "shared session" in localhost, it works, so I think my problem is domain related.
Any ideas ? Thanks.
Hello,
Regarding the following MongoStore structure:
store: new MongoStore({
db: settings.db
})
My service has multiple databases (each client has access to its own) and I'd like to store them while their respective session is active. Is MongoStore limited to one database, or can I save multiple ones? I'm looking for something like this:
store: new MongoStore({
dbA: db // (i.e. appleStuff),
dbB: db // (i.e. googleStuff),
dbC: db // (i.e. twitterStuff)
})
Is there some support that would allow me to store multiple connections? Thanks!
Says no compatible version is found.
Started getting this error with Node 0.4.9 and the latest version of connect-mongo, any ideas?
TypeError: Cannot call method 'findOne' of null
at MongoStore.get (/home/myapp/node_modules/connect-mongodb/lib/connect-mongodb.js:95:15)
at Object.session as handle
Hello,
I am getting a lot of empty sessions in my mongo database, probably on every request (or very often). Here is an example:
{
"_id": "oThxLcz3PtztDWVxcKZvoADC",
"session": "{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"passport":{}}",
"expires": {
"$date": "2013-07-10T22:45:52.383Z"
}
}
As you can see, there is no user defined in the . I read in another issue that it might be a difference of time between the server and the client so the cookies are expiring instantly but that's not the case, the session are working fine. Any idea ? I don't want to pay extra storage on my database.
I'm having an issue occasionally when heroku restarts my application. It's starts with this error:
132 <13>1 2012-04-20T04:06:36+00:00 d. app web.1 - - TypeError: Cannot call method 'update' of null
173 <13>1 2012-04-20T04:06:36+00:00 d. app web.1 - - at MongoStore.set (/app/node_modules/connect-mongodb/lib/connect-mongodb.js:145:15)
194 <13>1 2012-04-20T04:06:36+00:00 d. app web.1 - - at Session.save (/app/node_modules/express/node_modules/connect/lib/middleware/session/session.js:83:25)
201 <13>1 2012-04-20T04:06:36+00:00 d. app web.1 - - at ServerResponse. (/app/node_modules/express/node_modules/connect/lib/middleware/session.js:280:21)
162 <13>1 2012-04-20T04:06:36+00:00 d. app web.1 - - at ServerResponse.send (/app/node_modules/express/lib/response.js:108:8)
162 <13>1 2012-04-20T04:06:36+00:00 d. app web.1 - - at ServerResponse._render (/app/node_modules/express/lib/view.js:442:10)
161 <13>1 2012-04-20T04:06:36+00:00 d. app web.1 - - at ServerResponse.render (/app/node_modules/express/lib/view.js:318:17)
And then after that the app goes into an infinite loop with this error message:
131 <13>1 2012-04-20T04:06:36+00:00 d. app web.1 - - Error: Can't set headers after they are sent.
136 <13>1 2012-04-20T04:06:36+00:00 d. app web.1 - - at ServerResponse. (http.js:523:11)
185 <13>1 2012-04-20T04:06:36+00:00 d. app web.1 - - at ServerResponse.setHeader (/app/node_modules/express/node_modules/connect/lib/patch.js:62:20)
181 <13>1 2012-04-20T04:06:36+00:00 d. app web.1 - - at IncomingMessage.next (/app/node_modules/express/node_modules/connect/lib/http.js:165:13)
161 <13>1 2012-04-20T04:06:36+00:00 d. app web.1 - - at ServerResponse.render (/app/node_modules/express/lib/view.js:328:16)
110 <13>1 2012-04-20T04:06:36+00:00 d. app web.1 - - at /app/app.js:75:11
Until eventually I get memory exceeded errors and Heroku kills the app.
I'm using the MongoHQ add-on for the mongo store. Here is my app configuration:
mongo_url = process.env["MONGOHQ_URL"] || "mongodb://localhost/mydb";
app.configure(function(){
app.use(express.logger());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('cookie'));
app.use(express.session({
key:'sid'
, secret: 'secret'
, cookie: { path: '/', maxAge: 60000000 * 5,secret:"1202nitsua" }
, store: new mongoSessionStore({
url: mongo_url
})
}));
app.use(express.static(path + '/public'));
});
app.configure('production',function(){
mongoose.connect(process.env["MONGOHQ_URL"]);
app.use(express.errorHandler());
});
Please let me know if I'm doing something wrong.
Thanks
Sorry we can't quite pinpoint what broke it, but some combination of updated packages started throwing the following error:
host and port must be specified
from connection_pool.js:8
So we did a quick fix by making connect-mongo.js:43
be this:
options.port = parseInt(db_url.port);
to handle the case of a url being passed into the MongoStore constructor, because url.parse
leaves port
as a string.
Error: Cannot find module 'connect-mongo'
When using stringify: false
, there is another object, session.cookie.data
, that duplicates most of the properties under session.cookie
.
In addition, both session.cookie.expires
and session.cookie._expires
are present. both with the same value (null
in my case).
However, when using stringify: true
, none of this extra data is present.
stringify: false
var db = mongoose.createConnection(dblink);
//...
app.use(express.session({
secret: 'someSuperSecretSecret',
store: new MongoStore({
mongoose_connection: db,
stringify: false
})
}))
{
"_id" : "toCuYX028j26Nu0axrbohaDZ",
"session" : {
"cookie" : {
"path" : "/",
"_expires" : null,
"originalMaxAge" : null,
"httpOnly" : true,
"expires" : null,
"maxAge" : null,
"data" : {
"originalMaxAge" : null,
"expires" : null,
"secure" : null,
"httpOnly" : true,
"domain" : null,
"path" : "/"
}
},
"someSessionVarWeAdded" : "someSessionValue"
},
"expires" : ISODate("2013-04-11T18:26:41.511Z")
}
stringify: true
var db = mongoose.createConnection(dblink);
//...
app.use(express.session({
secret: 'someSuperSecretSecret',
store: new MongoStore({
mongoose_connection: db,
stringify: true
})
}))
{
"_id" : "Zb8JiLc9flqc43F/tefId2q3",
"session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},\"someSessionVarWeAdded\":\"someSessionValue\"}",
"expires" : ISODate("2013-04-11T19:15:36.643Z")
}
And the session JSON prettyprinted:
{
"cookie":{
"originalMaxAge":null,
"expires":null,
"httpOnly":true,
"path":"/"
},
"someSessionVarWeAdded":"someSessionValue"
}
Per @mmagi's comment on #63 (comment), as part of PR #74, the session.cookie
property is set to the result of cookie.toJSON()
, which removes the methods that are expected elsewhere.
I'm using passport+facebook and connect-mongo to store the session in the database.
I can see that is being set, all good when I browser through the pages, but once i close the browser and open again, it creates a new session.
Anyone can give me some guidance?
My code is
app.use(express.session({
secret: 'fdb708866db78951baa3f5c8737d1cc6',
cookie: {
maxAge: new Date(Date.now() + (90 * 24 * 60 * 60 * 1000))
},
store: new MongoStore(
{
db: 'fbtesting',
host: 'localhost',
port: 27017,
collection: 'usersessions' // optional, default: sessions
},
function(err){
console.log(err || 'connect-mongodb setup ok');
})
}));
(node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.
and many message later
RangeError: Maximum call stack size exceeded
NodeJS crashes
In the following code I use existing db object:
var mongoClient = new MongoClient(new Server('localhost', 27017, {auto_reconnect: true}));
mongoClient.open(function (err, mongoClient) {
var db = mongoClient.db('db_name');
db.authenticate('user', 'password', function () {err, result} {
if (err || !result) return console.log('error');
app.use(express.session({
store: new MongoStore({
db: db
})
});
});
});
I think the problem in https://github.com/kcbanner/connect-mongo/blob/master/lib/connect-mongo.js#L149 because here not nessesary check openCalled because I use existing object. So if I replace that line to just
this._get_collection(callback)
All works fine
npm says:
No compatible version found: connect-mongo
Hi,
When My App Tries To Connect To The DB I Get This Error:
/Users/Ari/Dev/ArisGame/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/server.js:529
throw err;
^
Error: Error setting TTL index on collection : sessions
at module.exports._get_collection (/Users/Ari/Dev/ArisGame/node_modules/connect-mongo/lib/connect-mongo.js:137:23)
at Db.ensureIndex (/Users/Ari/Dev/ArisGame/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:1227:28)
at Db.indexInformation (/Users/Ari/Dev/ArisGame/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:1371:30)
at Cursor.toArray (/Users/Ari/Dev/ArisGame/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/cursor.js:156:22)
at Cursor.nextObject.self.queryRun (/Users/Ari/Dev/ArisGame/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/cursor.js:611:39)
at Cursor.close (/Users/Ari/Dev/ArisGame/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/cursor.js:939:5)
at Cursor.nextObject.commandHandler (/Users/Ari/Dev/ArisGame/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/cursor.js:611:21)
at Db._executeQueryCommand (/Users/Ari/Dev/ArisGame/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:1709:18)
at g (events.js:192:14)
at EventEmitter.emit (events.js:126:20)
I'm Sorry,
This Is All I Really Know
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.