kcbanner/connect-mongo — pull request #45 by ifElser (2012-10-10 14:13:49+00:00)
Title: set session without destruct possible additional data in session document

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:
```javascript
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
```javascript
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