Mongodb通过自定义ID查找会话集合的结果

我正在使用Mongojs库,它是mongodb库周围的薄包装。 我想在会话集合中查找一些查询,这意味着我使用mongo来存储会话(connect-mongo)。

问题是这样的

db.sessions.find({}, cb); -- returns all the sessions 

当我尝试通过从req.sessionID – string中获取的id来查找指定的会话时,这将始终返回null

 db.sessions.findOne({ _id: req.sessionID }, cb); -- yes the seesionId exists, when i execute this query manually it works 

还尝试了“mongodb”库来直接连接。

 var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Code = require('mongodb').Code, BSON = require('mongodb').pure().BSON, assert = require('assert'); var db = new Db(session.db, new Server(session.host, session.port, {auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false}); function findBySid(sid, cb) { db.close(); db.open(function(err, db) { db.collection('sessions').findOne({ _id: sid }, function(err, session) { cb(err, session); }); }) 

结构本身看起来像这样,由连接mongo创build

 > db.sessions.find({ _id: 'QFtHqaTdtg5kucwvBmY3BZ7m' }).pretty() { "_id" : "QFtHqaTdtg5kucwvBmY3BZ7m", "session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"domain\":\"asad.\",\"path\":\"/\"}}", "expires" : ISODate("2013-08-12T12:34:49.271Z") } 

其实Mongo文件保存为

  { "_id" : ObjectId("51ecdea131ce0986e06e91fe"),....} 

所以你必须找出如下

 db.newcol.find({_id:ObjectId("51ecdea131ce0986e06e91fe")}); 

下面的shell输出将解释。

  >db.newcol.find({_id:51ecdea131ce0986e06e91fe}); Mon Jul 29 18:25:54.563 JavaScript execution failed: SyntaxError: Unexpected token ILLEGAL > db.newcol.find({_id:"51ecdea131ce0986e06e91fe"}); //No output empty > db.newcol.find({_id:ObjectId("51ecdea131ce0986e06e91fe")}); { "_id" : ObjectId("51ecdea131ce0986e06e91fe"), "name" : "karthick.k", "email" : "karthdfgdf@gmail.com", "phone_no" : "6666666666" } 

所以相应地构build你的查询。