1

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

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
Larry Hipp
  • 6,205
  • 3
  • 26
  • 31
  • When you say *"..I try to delete a document.."* then what do you mean here? Are you calling `.destroy()` on the session or doing something else? Specifically, have you set up a "mongoose" model to the session store and trying to manipulate through that? – Blakes Seven Aug 18 '15 at 02:46
  • Yes. I have a mongoose model and I am using Model.remove() – Larry Hipp Aug 18 '15 at 02:48

1 Answers1

2

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.

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
  • Thanks, that solved my cast error. req.session.destroy() doesn't remove the document from the database. After I call req.session.destroy() I'm attempting to delete the document from the db manually to ensure the session is truly gone. – Larry Hipp Aug 18 '15 at 03:01
  • @LarryHipp I ddi just quickly set up a vanilla install and swapped out `genid` as `{ genid: function(req) { return uuid.v4() } }` in the configuration using the `node-uuid` package. Everything works fine for me. I would suggest that you have other configuration issues to look at if this is not working for you. You can always post another question about that if you cannot find the issue. – Blakes Seven Aug 18 '15 at 03:05