Larry Hipp Larry Hipp - 2 months ago 25
Node.js Question

Manually deleting connect-mongo session by _id cast error

I'm attempting to manually delete a document from the connect-mongo sessions collection. When I try to delete a document I get the following error:


message: 'Cast to ObjectId failed for value "gl9-V-bjAjqv2Nwdf9vHPLN_Fnnl4Thz" at path "_id"'


express-session uses the following function to generate a session id:

function generateSessionId(sess) {
return uid(24);
}


The session generated from this function is making it way into the _id property of the sessions document. However when you try and find or delete the document by the generated id you get the error.

The mongodb docs say the _id should be


ObjectId is a 12-byte BSON type
ObjectId


I've tried to override the session id using the genid option on the session, but the override doesn't make it into the database.

How can I get a valid _id onto the document or query the document with an invalid _id?

Thanks!

My Infrastructure: Express 4.10, Node v0.12.7, Compose.io, connect-mongo, express-session

Answer

Okay so your problem here is the mongoose model you are using to delete documents from the session store. You probably should be calling req.session.destroy() or setting up TTL to remove expired sessions instead.

But basically, mongoose is expecting the "type" of the _id field to be an ObjectId and as such "autocasts". The mongo-connect middleware itself does not use mongoose methods, but talks to the underlying driver methods instead. So it does not have this problem when using it's internal methods.

Your mongoose schema definition should therefore look something like this:

var sessionSchema = new Schema({
    "_id": String,
    "session": String
},{ "_id" false });

Or at the very least contain { "_id": false } in order to remove the default autocasting behavior.